从静态非UI线程访问控件?

时间:2017-01-15 04:53:36

标签: c#

我有一个TCP客户端连接到服务器。连接后,应将标签更改为“已连接”。我遇到的问题是,当我创建一个线程时,无论如何都是静态的。

public static Thread waitForConnectionThread = new Thread(waitForConnection);

这意味着它将运行的方法也必须是静态的,这反过来又导致我无法访问UI控件。

public static void waitForConnection()
    {
        server.Start();
        client = server.AcceptTcpClient();
        labelControl1.Text = "Connected";  <-----------------
    }

我也尝试过Control.Invoke,但由于我在静态线程上,我无法让它工作。有可能解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

创建如下所示的类:

public class TcpConnect
{
    public Thread waitForConnectionThread;

    public event EventHandler ClientConnected;

    public TcpConnect()
    {
        waitForConnectionThread = new Thread(waitForConnection);
    }

    private void waitForConnection()
    {
        server.Start();
        client = server.AcceptTcpClient();
        RaiseClientConnected(new EventArgs());
    }

    protected void RaiseClientConnected(EventArgs args)
    {
        if (ClientConnected != null)
        {
            ClientConnected(this, args);
        }
    }
}

然后在表单中创建一个实例并将事件处理程序附加到创建的类中的ClientConnected事件,如下所示:

        TcpConnect tcpConnect = new TcpConnect();
        tcpConnect.ClientConnected += tcpConnect_ClientConnected;

并且事件处理程序应该调用更新标签方法,如下所示:

void tcpConnect_ClientConnected(object sender, EventArgs e)
    {
        if (this.InvokeRequired)
        {
            //then it is called from other thread, so use invoke method to make UI thread update its field
            this.Invoke(new Action(() => UpdateLabelText()));
        }
        else
        {
            //then it is called from UI and can be updated directly
            UpdateLabelText();
        }

    }

    private void UpdateLabelText()
    {

        labelControl1.Text = "Connected";
    }

希望这很有用。