Chapter 17. Multithreading

Multithreading enables an application to execute several pieces of code simultaneously. There are two common reasons for doing this. One is to exploit the computer’s parallel processing capabilities—multicore CPUs are now more or less ubiquitous, and to realize their full performance potential, you’ll need to provide the CPU with multiple streams of work to give all of the cores something useful to do. The other usual reason for writing multithreaded code is to prevent progress from grinding to a halt when you do something slow, such as reading from disk. Multithreading is not the only way to solve that second problem—asynchronous techniques can be preferable. However, asynchronous APIs often use multiple threads, so it’s important to be aware of .NET’s threading mechanisms in any case.

C# 5.0 introduces new language features for supporting asynchronous work. Asynchronous execution doesn’t necessarily mean multithreading, but the two are often related in practice, and I will be describing some of the asynchronous programming models in this chapter. However, this chapter focuses on the threading foundations. I will describe the language-level support for asynchronous code in Chapter 18.

Threads

Windows allows each process to contain multiple threads. Each thread has its own stack, and the operating system presents the illusion that a thread gets a whole CPU hardware thread to itself. (See the next sidebar, .) You can create far more operating system threads ...

Get Programming C# 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.