C Sharp

Multithreaded Programming

Technically speaking, threads are not specific to C#; most C# authors tend to stay away from the topic for that reason. Although I've tried to stay very specific to C#, the general subject of multithreading is one most programmers should be familiar with when learning this new language.

I certainly can't cover the entire range of threading-related issues in one tutorial, but I will cover the basics and even some intermediate-to-advanced issues regarding the aborting, scheduling, and lifetime management of threads. I'll also discuss thread synchronization with the System.Monitor and System.Mutex classes and the C# lock statement.

Using a single-threaded application is like shopping in a supermarket with a single cashier. Employing only one cashier is less expensive for the store owner and the cashier can handle relatively low levels of traffic, but once the store announces double-coupon day and the checkout line gets longer and longer, some customers become extremely unhappy. What we have here is your standard bottleneck scenario: too much data and too small a conduit. The answer, of course, is to hire more cashiers.

And so it is for threading and applications. Multithreading allows an application to divide tasks such that they work independently of each other to make the most efficient use of the processor and the user's time. However, if you're new to multithreaded programming, there's a caveat: threading is not the right choice for all applications and can sometimes even slow an application down. So, it's paramount that along with learning the syntax of multithreading you also understand when to use it. To that end, I've included a section at the end of this chapter ("Threading Guidelines") to help you determine when creating multiple threads in your applications is the way to go. For now, let's start looking at how threading is implemented in the Microsoft .NET Framework.