How to post a UI message from a worker thread in C#

家住魔仙堡 提交于 2019-12-04 17:17:57
Matt Davis

In the event callback from the completed thread, use the InvokeRequired pattern, as demonstrated by the various answers to this SO post demonstrate.

C#: Automating the InvokeRequired code pattern

Another option would be to use the BackgroundWorker component to run your thread. The RunWorkerCompleted event handler executes in the context of the thread that started the worker.

i normally do something like this

void eh(Object sender,
EventArgs e)
{
   if (this.InvokeRequired)
   {
      this.Invoke(new EventHandler(this.eh, new object[] { sender,e });
       return;
    }  
    //do normal updates
}

The Control.Invoke() or Form.Invoke() method executes the delegate you provide on the UI thread.

You can use the Invoke function of the form. The function will be run on the UI thread.

EX :

...
MethodInvoker meth = new MethodInvoker(FunctionA);
form.Invoke(meth);
....

void FunctionA()
{
   testField.Text = "Ready". 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!