在Windows窗体中调用

Luk*_*son 2 .net invoke visual-c++ winforms

有没有人有学习资源的链接使用Invoke?

我正在努力学习,但我看到的所有例子都无法适应我的目的.

ira*_*hil 9

你尝试过MSDN Control.Invoke吗?

我刚刚编写了一个WinForm应用程序来演示Control.Invoke.创建表单时,在后台线程上启动一些工作.完成该工作后,更新标签中的状态.

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();
}
Run Code Online (Sandbox Code Playgroud)