问题
I'm writing a simple winforms app in C#. I create a worker thread and I want the main window to respond to the tread finishing its work--just change some text in a text field, testField.Text = "Ready". I tried events and callbacks, but they all execute in the context of the calling thread and you can't do UI from a worker thread.
I know how to do it in C/C++: call PostMessage from the worker thread. I assume I could just call Windows API from C#, but isn't there a more .NET specific solution?
回答1:
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.
回答2:
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
}
回答3:
The Control.Invoke() or Form.Invoke() method executes the delegate you provide on the UI thread.
回答4:
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".
}
回答5:
Using C# MethodInvoker.Invoke() for a GUI app... is this good?
来源:https://stackoverflow.com/questions/5316296/how-to-post-a-ui-message-from-a-worker-thread-in-c-sharp