在调用Windows窗体窗体、Windows

2023-09-06 19:33:32 作者:陌上。少年。

有没有人有一个链接,使用调用学习资源?

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 been unable to adapt for my purposes.

推荐答案

您是否尝试过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();
}