Thread Management
The .NET framework offers numerous ways for developers to manage threads. For example, you can create threads using both Thread and ThreadStart types. The code below shows an example:
namespace ThreadingInDotNet
{
class Program
{
static void Main(string[] args)
{
ThreadSafeType tst = new ThreadSafeType();
Thread t1 = new Thread(new
ThreadStart(tst.PrintThreadId));
Thread t2 = new Thread(new
ThreadStart(tst.PrintThreadId));
t1.Start();
t2.Start();
}
}
class ThreadSafeType
{
public void PrintThreadId()
{
Console.WriteLine("Thread id : " +
Thread.CurrentThread.ManagedThreadId);
}
}
}
The ParameterizedThreadStart delegate was introduced in the .NET Framework 2.0. It lets you pass an object containing data to a thread when calling a
Thread.Start method overload.
You can use the Managed Thread Pool to obtain information about background threads. The ThreadPool class provides applications with a pool of managed worker threads. Here are few points to note about using ThreadPool class:
- All ThreadPool threads are background threads.
- All ThreadPool threads are in the multithreaded apartment, which means multiple threads can access the same instance of an object at any given point in time, and the object itself is responsible for thread synchronization.
- There can be only one ThreadPool per managed process.
- There is a limit to the number of threads that can be queued and the number of threads per processor that can be active while using the ThreadPool class.
Thread States
A thread is always in at least one of the possible states shown in Table 1.
Table 1. Possible Thread States: The table shows all the possible states for a thread.
Thread State |
Description |
Unstarted |
The thread has been created but has not yet begun executing. |
Running |
The thread is executing. This state begins when a program calls Thread.Start. |
Aborted |
This state results from a Thread.Abort call. The thread is dead and will move to the Stopped state. |
Suspended |
Thread execution has been halted by a Thread.Suspend call. |
WaitSleepJoin |
The thread is blocked, and waiting for some condition to occur. |
Stopped |
The thread has stopped, and cannot restart. |
StopRequested, SuspendRequested, AbortRequested |
These are intermittent states that occur before a thread moves to one of the final states of Stopped, Suspended, and Aborted, respectively. |
Background |
Occurs when the thread is a background thread. |
Using this basic thread management information, you can explore the various techniques for thread synchronization.