I am using
System.Threading.ThreadPool.QueueUserWorkItem(x => MyMethod(param1, param2, param3, param4, param5));
I want to call the following method from the main thread every time the call to MyMethod is completed:
UpdateGui()
{
}
How do I do that?
Thanks!
Keep a global counter of work items queued and an object to protect it:
Every time a task is added increment the counter:
At the end of
MyMethoddecrement the counter and signal the main thread:In the main thread (assuming this is not the GUI thread!):
This way you also have a barrier to wait for all pending tasks to finish.
In case you don’t want to wait, just skip the main thread completely and call
UpdateGUIto forward updates to the GUI thread whenMyMethodfinishes.Note that inside
MyMethodyou should have some form ofDispatcher.BeginInvoke(WPF) orControl.BeginInvoke(WinForms) otherwise you cannot update the GUI safely!