3

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?

Bartosz Milewski
  • 11,012
  • 5
  • 36
  • 45
  • Control.BeginInvoke() is the *exact* equivalent to PostMessage(). With the added advantage that you can pick the target method and pass it any arguments you want. – Hans Passant Mar 15 '11 at 18:58

5 Answers5

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.

Community
  • 1
  • 1
Matt Davis
  • 45,297
  • 16
  • 93
  • 124
1

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
}
madmik3
  • 6,975
  • 3
  • 38
  • 60
0

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

Scott Pedersen
  • 1,311
  • 1
  • 10
  • 19
0

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". 
}
Kipotlov
  • 518
  • 3
  • 10
0

Using C# MethodInvoker.Invoke() for a GUI app... is this good?

Community
  • 1
  • 1
Dekryptid
  • 1,062
  • 1
  • 9
  • 21