Chapter 7. Multithreading Gotchas
Multithreading is a powerful tool. It is also complex—I have enjoyed many a pizza at the office during lengthy debugging sessions. There are methods and facilities that work well only when used in a certain way. It is like tightrope walking; you can’t afford to slip to either side. Fully understand the capabilities, behavior, and limitations of the API before using it.
Thread class provides a number of methods that are useful, a few that are not so useful, and some that are quite dangerous. Also, you have the options of creating a thread yourself, using one from the thread pool, or even using asynchronous features provided by the
WinForms framework. Which one should you choose and why? What are the consequences of choosing one over the other? What happens if an exception is thrown from within a thread? How is this handled? Is it handled at all? What is the lifetime of a thread you create, and how can you control it? What happens when a thread is terminated? What about cleanup of resources? These are all questions you should ask before using the API.
In this chapter, I address these questions and provide answers that will steer you clear of the perils. I discuss general problems with threading, the thread pool, asynchronous calls using delegates, and threading problems related to Windows Forms [Griffiths03] and Web Services [Ballinger03, Ferrara02].
GOTCHA #48 The Thread classThread class
Thread class provides a number of methods and properties ...