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?
In the event callback from the completed thread, use the
InvokeRequiredpattern, as demonstrated by the various answers to this SO post demonstrate.C#: Automating the InvokeRequired code pattern
Another option would be to use the
BackgroundWorkercomponent to run your thread. TheRunWorkerCompletedevent handler executes in the context of the thread that started the worker.