首页 > 解决方案 > 无法更改 TextBox 文本

问题描述

我想在我的 Backgroundworker 中更改 TextBox 的文本,但它不起作用,我在代码中找不到错误。

背景工作者:

class Check_Server
{
    WebSocket webSocket = new WebSocket("ws://localhost:8548");
    private Form1 Form1;

    public void Check_WebSocket(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        while (!worker.CancellationPending)
        {
            Console.WriteLine("checking connection");
            if (webSocket.IsAlive == true)
            {
                Console.WriteLine("connected");
            }
            else
            {
                Console.WriteLine("not connected");
                
                Form1 form = new Form1();
                form.SetText("XYZ");
                MakeNewConnection();
            }
        }
    }

    void MakeNewConnection()
    {
        webSocket.Connect();      
        Thread.Sleep(10000);
    } 
}

形式:

public void SetText(string text)
{
    if (InvokeRequired)
    {
        this.Invoke((MethodInvoker)delegate () { SetText(text); });
        return;
    }
    
    textBox1.Text += text;
}

标签: c#winforms

解决方案


你不显示你的表格。添加form.Show()form.ShowDialog(),具体取决于您是否要等到用户关闭表单。

此外,我发现此扩展方法对于对控件进行线程安全更改非常有用。像这样使用它:textBox1.InvokeSave(() => textBox1.Text += text);.

public static partial class ControlExtensions
{
    public static void InvokeSave(this Control control, Action action)
    {
        Delegate del = action;

        try
        {
            if (control.InvokeRequired)
            {
                control.Invoke(del);
            }
            else action();
        }
        catch (ObjectDisposedException)
        {
            // guess do nothing is fine then
        }
    }
}

推荐阅读