[Previous] [Contents] [Next]

Costs Outweigh Benefits

As you saw in "Thread Safety and Synchronization," writing multithreaded applications takes a bit of time and effort in the design of the code. There will be times when the slight gains enjoyed by having multiple threads just isn't worth the extra time required to make your code thread-safe.

You Haven't Benchmarked Both Cases

If you're new to multithreaded programming, it might surprise you to find that often the overhead required by CPU thread creation and scheduling to achieve modest gains in CPU utilization can actually result in single-threaded applications running faster! It all depends on what you're doing and if you're truly splitting independent tasks into threads. For example, if you have to read three files from disk, spawning three threads won't do you any good because each has to use the same hard disk. Therefore, always be sure to benchmark a prototype of both a single-threaded and multithreaded version of your system before going through the extra time and cost of designing around a solution that might actually backfire in terms of performance.

No Good Reason Why You Should

Using multiple threads should not be the default. Because of the inherent complexities of writing multithreaded applications, you should always default to single-threaded code unless you have a good reason to do otherwise.

Summary

Multithreading allows applications to divide tasks so that they work independently of each other to make the most efficient use of the processor's time. However, adding multiple threads to an application is not the right choice in all situations and can sometimes slow the application down. Thread management and creation in C# is done through the System.Threading.Thread class. An important concept related to the creation and use of threads is thread safety. Thread safety means that the members of an object always maintain a valid state when used concurrently by multiple threads. It's important that along with learning the syntax of multithreading you also understand when to use it: to increase concurrency, to simplify design, and to better utilize CPU time.

[Previous] [Contents] [Next]