01-05-2012, 11:08 AM
Threading in C#
threading.pdf (Size: 1.16 MB / Downloads: 36)
Introduction and Concepts
C# supports parallel execution of code through multithreading. A thread is an independent execution path, able to run
simultaneously with other threads.
A C# client program (Console, WPF, or Windows Forms) starts in a single thread created automatically by the CLR and
operating system (the “main” thread), and is made multithreaded by creating additional threads. Here’s a simple example
and its output:
How Threading Works
Multithreading is managed internally by a thread scheduler, a
function the CLR typically delegates to the operating system. A
thread scheduler ensures all active threads are allocated appropriate
execution time, and that threads that are waiting or blocked (for
instance, on an exclusive lock or on user input) do not consume
CPU time.
On a single-processor computer, a thread scheduler performs timeslicing—
rapidly switching execution between each of the active
threads. Under Windows, a time-slice is typically in the tens-ofmilliseconds
region—much larger than the CPU overhead in
actually switching context between one thread and another (which
is typically in the few-microseconds region).
Threads vs Processes
A thread is analogous to the operating system process in which your
application runs. Just as processes run in parallel on a computer,
threads run in parallel within a single process. Processes are fully
isolated from each other; threads have just a limited degree of
isolation. In particular, threads share (heap) memory with other threads running in the same application. This, in part, is
why threading is useful: one thread can fetch data in the background, for instance, while another thread can display the
data as it arrives.
Creating and Starting Threads
As we saw in the introduction, threads are created using the Thread class’s constructor, passing in a ThreadStart
delegate which indicates where execution should begin. Here’s how the ThreadStart delegate is defined:
public delegate void ThreadStart();
Calling Start on the thread then sets it running. The thread continues until its method returns, at which point the thread
ends. Here’s an example, using the expanded C# syntax for creating a TheadStart delegate: