且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在调用Windows窗体

更新时间:2023-12-06 12:15:40

您是否尝试过MSDN的 Control.Invoke

Did you try MSDN Control.Invoke

我刚写了一个小的WinForm程序来演示Control.Invoke。 在创建形式,开始在后台线程一些工作。之后,工作完成后,在更新标签的状态。

I just wrote a little WinForm application to demonstrate Control.Invoke. When the form is created, Start some work on background thread. After that work is done, Update the status in a label.

public Form1()
{
    InitializeComponent();
    //Do some work on a new thread
    Thread backgroundThread = new Thread(BackgroundWork);
    backgroundThread.Start();
}        

private void BackgroundWork()
{
    int counter = 0;
    while (counter < 5)
    {
        counter++;
        Thread.Sleep(50);
    }

    DoWorkOnUI();
}

private void DoWorkOnUI()
{
    MethodInvoker methodInvokerDelegate = delegate() 
                { label1.Text = "Updated From UI"; };

    //This will be true if Current thread is not UI thread.
    if (this.InvokeRequired)
        this.Invoke(methodInvokerDelegate);
    else
        methodInvokerDelegate();
}