C Sharp

Thread Safety and the .NET Classes

One question I see quite often in the newsgroups and mailing lists is whether all the .NET System.* classes are thread-safe. The answer is "No, and they should not be." You could severely cripple a system's performance if all classes serialized access to their functionality. For example, imagine attempting to use one of the collection classes if it obtained a monitor lock each time you called its Add method. Now let's say you instantiate a collection object and add about a thousand objects to it. Performance would be dismal-to the point of making the system unusable.

Threading Guidelines

When do you need to use threads, and when is it best, if ever, to avoid them like the plague? In this section, I'll describe both some common scenarios in which threads can be extremely valuable to your application and some situations in which it would be best to avoid using multiple threads.

When to Use Threads

You should use threads when you are striving for increased concurrency, simplified design, and better utilization of CPU time, as described in the following sections.

Increased Concurrency

Very often applications need to accomplish more than one task at a time. For example, I once wrote a document retrieval system for banks that accessed data from optical disks that were stored in optical disk jukeboxes. Imagine the massive amounts of data we're talking about here; picture a jukebox with one drive and 50 platters serving up gigabytes of data. It could sometimes take as long as 5 to 10 seconds to load a disk and find the requested document. Needless to say, it wouldn't exactly be the definition of productivity if my application blocked user input while it did all this. Therefore, to deal with the user input case, I spun off another thread to do the physical work of retrieving the data, allowing the user to continue working. This thread would notify the main thread when the document was loaded. This is a great example of having independent activities-loading a document and handling the UI-that can be handled with two separate threads.