开发者

Invoke in Windows Forms

开发者 https://www.devze.com 2023-03-19 22:40 出处:网络
Does anyone have a link to a learning resource for using Invoke? I\'m trying to learn but all the examples I have seen I have bee开发者_StackOverflown unable to adapt for my purposes.Did you try MSD

Does anyone have a link to a learning resource for using Invoke?

I'm trying to learn but all the examples I have seen I have bee开发者_StackOverflown unable to adapt for my purposes.


Did you try MSDN 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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消