Today I had to fix some old VB.NET 1.0 code which is using thread. The problem was to update UI elements from the worker thread instead of UI-thread. It took me a while to learn that I can use arguments with InvokeRequired to detect the problem.
In addition to the above concurrent amendment problem, there are deadlock, race conditions, etc. Debugging / Fixing Threading Problems is a pain, I am wondering how can I reduce coding errors / flaws in this area and how can I easily find any of these things. Therefore, what I am asking is:
- Is there a good pattern to follow while writing multi-threading code? What else is not?
- Which technology do you use to debug threading issues?
Please provide some example code if applicable and answer should be related to Net Framework (any version).
This can be an large scale list - for more detail Read Duffy's excellent "". It is quite a brain dump ...
- Try to avoid calling in a significant part of the code when you lock it
- Avoid locking on references,
- If you ever need to get more than one lock, always get those locks in one order
- Where appropriate, Use an irreversible type - they can be freely shared between threads
- In addition to the unchangeable types, try to avoid the need to share data between threads
- Avoid trying to create your own threadsof; Most types are not required, and usually the code that the data needs to be shared will need to control locking
- In the WinForms app:
- Run the UI Thread Or blocking operations
- Do not touch the UI from any thread other than the UI thread. Avoid (thread-thread-statics) where possible - they can give unexpected behavior to ASP in particular (background worker, control, use invoke / beeroinwoke)
- Net where can be requested by different threads (Search for "Thread Execution" and ASP.NET)
- Do not try to be smart
- your Document types of threading models (and thread protection)
- Monitor should be almost always used in combination with some kind of probe, while loop (i.e., when i can not move forward) in some time monitor Wait (Monitor))
- Consider the difference between the monitor. Pulse and monitor. Pulsar carefully every time you use one of them.
- Inserting threads. Sleep to overcome the problem, there is never a real improvement.
- Take a look at "Parallel Extensions" and the parallel extension is going to be part of .NET 4.0 as a way to simplify the "coordinate and concurrency runtime" interaction.
In the case of debugging, I do not have much advice using the thread. Sleep can work to promote race conditions and opportunities to see deadlocks, but you have to think deeply in saying this where to put it. Logging is very easy, but do not forget that the code goes into a kind of quantum state - seeing through logging, changing its behavior is almost bound!
Comments
Post a Comment