Today I had to fix some older VB.NET 1.0 code which is using threads. The problem was with updating UI elements from the worker thread instead of the UI-thread. It took me some time to find out that I can use assertions with InvokeRequired to find the problem.
Besides the above mentioned concurrent modification problem, there are deadlocks, race conditions, etc. one could run into. As debugging/fixing threading problems is a pain, I’m wondering how I could reduce coding errors/faults in this area and how I could easier find any of them. So, what I’m asking for, is:
- Are there any good patterns to follow when writing multi-threading code? What are the Dos and Don’ts?
- What techniques do you use to debug threading problems?
Please provide some example code if applicable and possible. The answers should be related to the .NET framework (any version).
This could be a massive list – read Joe Duffy’s excellent ‘Concurrent Programming On Windows‘ for much more detail. This is pretty much a brain dump…
In terms of debugging, I don’t have very much advice. Using Thread.Sleep to boost the chances of seeing race conditions and deadlocks can work, but you’ve got to have quite a reasonable understanding of what’s wrong before you know where to put it. Logging is very handy, but don’t forget that the code goes into a sort of quantum state – observing it via logging is almost bound to change its behaviour!