Bartosz Milewski
Bartosz Milewski

Reputation: 11650

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

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?

Upvotes: 3

Views: 9486

Answers (5)

madmik3
madmik3

Reputation: 6983

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
}

Upvotes: 1

Kipotlov
Kipotlov

Reputation: 518

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". 
}

Upvotes: 0

Matt Davis
Matt Davis

Reputation: 46062

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.

Upvotes: 1

Scott Pedersen
Scott Pedersen

Reputation: 1311

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

Upvotes: 0

Related Questions