|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
Using Threading (C# Programming Guide)
By default, a C# program has one thread. This thread executes the code in the program starting and ending with the Main method. Every command executed by Main--either directly or indirectly--is performed by the default, or primary thread, and this thread terminates when Main returns. However, auxiliary threads can be created and used to execute code in parallel with the primary thread. These threads are often called worker threads.
Worker threads can be used to perform time-consuming or time critical tasks without tying up the primary thread. For example, worker threads are often used in server applications to fulfill incoming requests without waiting for the previous request to be completed. Worker threads are also used to perform "background" tasks in desktop applications so that the main thread--which drives user interface elements--remains responsive to user actions.
Multithreading solves problems with throughput and responsiveness, but it can also introduce resource-sharing issues such as deadlocks and race conditions. Multiple threads are best for tasks that require different resources such as file handles, network connections. Assigning multiple threads to a single resource is likely to cause synchronization issues, and having threads frequently blocked when waiting for other threads defeats the purpose of using multiple threads.
A common strategy is to use worker threads to perform time-consuming or time-critical tasks that do not require many of the resources used by other threads. Naturally, some resources in your program must be accessed by multiple threads. For these cases, the System.Threading namespace provides classes for synchronizing threads. These classes include Mutex, Monitor, Interlocked, and AutoResetEvent, and ManualResetEvent.
You can use some or all these classes to synchronize the activities of multiple threads, but some support for multi-threading is supported by the C# language. For example, the C# Lock Statement provides synchronization features through implicit use of Monitor.
The following topics demonstrate common multithreading techniques:
For more information, see: