C# Multithreading
Thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complex and time-consuming operations, then setting up different execution paths of threads is often beneficial, with each thread performing a specific task.
Threads are lightweight processes. A common example of using threads is the implementation of concurrent programming in modern operating systems. Using threads saves CPU cycles wastage and improves the efficiency of the application.
So far, the programs we have written run as a single process with a single thread of execution. However, such applications can only perform one task at a time. To perform multiple tasks simultaneously, it can be divided into smaller threads.
Thread Life Cycle
The thread life cycle begins when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution.
The following states are listed in the thread life cycle:
Unstarted State: When the thread instance is created but the Start method has not been called.
Ready State: When the thread is ready to run and waiting for CPU cycles.
Not Runnable State: A thread is not runnable in the following cases:
The Sleep method has been called.
The Wait method has been called.
Blocked by I/O operations.
Dead State: When the thread has completed execution or has been aborted.
Main Thread
In C#, the System.Threading.Thread class is used for thread operations. It allows the creation and access of individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread.
When a C# program starts execution, the main thread is automatically created. Threads created using the Thread class are called child threads of the main thread. You can access the thread using the CurrentThread property of the Thread class.
The following program demonstrates the execution of the main thread:
Example
using System;
using System.Threading;
namespace MultithreadingApplication
{
class MainThreadProgram
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
This is MainThread
Common Properties and Methods of the Thread Class
The following table lists some of the commonly used properties of the Thread class:
Property | Description |
---|---|
CurrentContext | Gets the current context in which the thread is executing. |
CurrentCulture | Gets or sets the culture for the current thread. |
CurrentPrincipal | Gets or sets the thread's current principal (for role-based security). |
CurrentThread | Gets the currently running thread. |
CurrentUICulture | Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at runtime. |
ExecutionContext | Gets an ExecutionContext object that contains information about the various contexts of the current thread. |
IsAlive | Gets a value indicating the execution status of the current thread. |
IsBackground | Gets or sets a value indicating whether or not a thread is a background thread. |
IsThreadPoolThread | Gets a value indicating whether or not the thread belongs to the managed thread pool. |
ManagedThreadId | Gets a unique identifier for the current managed thread. |
Name | Gets or sets the name of the thread. |
Priority | Gets or sets a value indicating the scheduling priority of a thread. |
ThreadState | Gets a value containing the states of the current thread. |
The following table lists some of the commonly used methods of the Thread class:
Number | Method Name & Description |
---|---|
1 | public void Abort() <br>Raises a ThreadAbortException on the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread. |
2 | public static LocalDataStoreSlot AllocateDataSlot() <br>Allocates an unnamed data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
3 | public static LocalDataStoreSlot AllocateNamedDataSlot(string name) <br>Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
4 | public static void BeginCriticalRegion() <br>Notifies the host that execution is about to enter a region of code where the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain. |
5 | public static void BeginThreadAffinity() <br>Notifies the host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread. |
6 | public static void EndCriticalRegion() <br>Notifies the host that execution is about to enter a region of code where the effects of a thread abort or unhandled exception are limited to the current task. |
7 | public static void EndThreadAffinity() <br>Notifies the host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread. |
8 | public static void FreeNamedDataSlot(string name) <br>Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
9 | public static Object GetData(LocalDataStoreSlot slot) <br>Retrieves the value from the specified slot on the current thread, in the current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
10 | public static AppDomain GetDomain() <br>Returns the current domain in which the current thread is running. |
11 | public static AppDomain GetDomainID() <br>Returns a unique application domain identifier. |
12 | public static LocalDataStoreSlot GetNamedDataSlot(string name) <br>Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
13 | public void Interrupt() <br>Interrupts a thread that is in the WaitSleepJoin thread state. |
14 | public void Join() <br>Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overload forms. |
15 | public static void MemoryBarrier() <br>Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses before the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier. |
16 | public static void ResetAbort() <br>Cancels an Abort requested for the current thread. |
17 | public static void SetData(LocalDataStoreSlot slot, Object data) <br>Sets data in the specified slot on the current thread, in the current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
18 | public void Start() <br>Starts a thread. |
19 | public static void Sleep(int millisecondsTimeout) <br>Makes the thread pause for a period of time. |
20 | public static void SpinWait(int iterations) <br>Causes a thread to wait the number of times defined by the iterations parameter. |
21 | public static byte VolatileRead( |
ref byte address ) public static double VolatileRead( ref double address ) public static int VolatileRead( ref int address ) public static Object VolatileRead( ref Object address ) Reads the field value. Regardless of the number of processors or the state of the processor cache, this value is the most recent one written by any processor in the computer. This method has different overload forms. Only some forms are shown here. | 22 | public static void VolatileWrite( ref byte address, byte value ) public static void VolatileWrite( ref double address, double value ) public static void VolatileWrite( ref int address, int value ) public static void VolatileWrite( ref Object address, Object value ) Writes a value to the field immediately, making the value visible to all processors on the computer. This method has different overload forms. Only some forms are shown here. | 23 | public static bool Yield() Causes the calling thread to execute another thread that is ready to run on the current processor. The operating system selects the thread to execute.
Creating Threads
Threads are created by extending the Thread class. The extended Thread class calls the Start() method to begin the execution of the child thread.
The following program demonstrates this concept:
Example
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts
Managing Threads
The Thread class provides various methods to manage threads.
The following example demonstrates the use of the sleep() method to pause a thread for a specific period.
Example
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
// Pause the thread for 5000 milliseconds
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds",
sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes
Destroying Threads
The Abort() method is used to destroy threads.
It throws a ThreadAbortException to abort the thread. This exception cannot be caught, and if there is a finally block, control is sent to the finally block.
The following program illustrates this:
Example
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
try
{
Console.WriteLine("Child thread starts");
// Count to 10
for (int counter = 0; counter <= 10; counter++)
{
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("Child Thread Completed");
}
catch (ThreadAbortException e)
{
Console.WriteLine("Thread Abort Exception");
}
finally
{
Console.WriteLine("Couldn't catch the Thread Exception");
}
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
// Stop the main thread for some time
Thread.Sleep(2000);
// Now abort the child thread
Console.WriteLine("In Main: Aborting the Child thread");
childThread.Abort();
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result: ``` In Main: Creating the Child thread Child thread starts 0 1 2 In Main: Aborting the Child thread Thread Abort Exception Couldn't catch the Thread Exception