How (not) to create a deadlock with the Thread.Join() method
In one of my projects I needed to be able to execute multiple tasks at the same time and show the results when all the tasks were finished.
The tasks included updating of the user interface. Since you cannot update a control on the user interface from a thread different than the thread that owns the control, you need to use the Control.Invoke method.
Control.Invoke(delegate method) executes the specified delegate on the thread that owns the control. So this way, you can have a second thread make a call to the main thread to update the user interface. So far so good.
The goal was to load multiple datasets in different threads and call a Control.Invoke for each dataset to bind it to a control on the form. After all the threads were finished, I wanted to show the form to the user.
To be able to check that all the threads were finished, I used the Thread.Join() method. This method blocks the main method until the thread finishes. If you create a loop that loops through all the threads you started and call Thread.Join() you are sure that all threads have finished.
The issue with this is that Thread.Join() blocks the main thread. So it also blocks the calls made via Control.Invoke. This is why you can't use Thread.Join() in combination with Control.Invoke. Pretty logic but if you don't realize what is going wrong, you can spent quite some time on it.
References:
0 comments:
Post a Comment