簡體   English   中英

從靜態非UI線程訪問控件?

[英]Accessing a Control From A Static Non-UI Thread?

我有一個TCP客戶端連接到服務器。 連接后,應將標簽更改為“已連接”。 我遇到的問題是,當我創建一個線程時,無論如何它都是靜態的。

public static Thread waitForConnectionThread = new Thread(waitForConnection);

這意味着它將運行的方法也必須是靜態的,這反過來又導致我無法訪問UI控件。

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

我也嘗試過Control.Invoke,但由於我在靜態線程上,我無法讓它工作。 有可能解決這個問題嗎?

創建如下所示的類:

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";
    }

希望這很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM