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).
Update: I asked a separate question for the debugging part here and accepted Jon Skeet's answer for the first question.