**
A **thread** is defined as the execution path of a program. Each thread defines a unique control flow. If your application involves complex and time-consuming operations, it is often beneficial to set up different execution paths for threads, with each thread performing a specific task.
Threads are **lightweight processes**. A common example of using threads is the implementation of parallel programming in modern operating systems. Using threads saves wasted CPU cycles while improving the efficiency of the application.
The programs we have written so far run as a single process with a single thread as the running instance of the application. However, such an application can only execute one task at a time. To execute multiple tasks simultaneously, it can be divided into smaller threads.
The thread lifecycle begins when an object of the `System.Threading.Thread` class is created and ends when the thread is terminated or completes execution.
The various states in a thread's lifecycle are listed below:
* **Unstarted State**: The state when a thread instance is created but the `Start` method has not been called.
* **Ready State**: The state when a thread is ready to run and is waiting for a CPU cycle.
* **Not Runnable State**: A thread is not runnable in the following situations:
* The `Sleep` method has been called.
* The `Wait` method has been called.
* Blocked by an I/O operation.
* **Dead State**: The state when a thread has completed execution or has been aborted.
In C#, the **`System.Threading.Thread`** class is used for thread operations. It allows creating and accessing 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 executing, the main thread is automatically created. Threads created using the **`Thread`** class are called by the main thread's child threads. You can access a thread using the `CurrentThread` property of the `Thread` class.
The following program demonstrates the execution of the main thread:
## Example
```csharp
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
The following table lists some 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 run time. |
| 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 a thread is a background thread. |
| IsThreadPoolThread | Gets a value indicating whether a 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 commonly used **methods** of the `Thread` class:
| No. | Method Name & Description |
| --- | --- |
| 1 | **`public void Abort()`** Raises a `ThreadAbortException` in 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()`** Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the `ThreadStaticAttribute` attribute instead. |
| 3 | **`public static LocalDataStoreSlot AllocateNamedDataSlot(string name)`** 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()`** Notifies the host that the execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain. |
| 5 | **`public static void BeginThreadAffinity()`** 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()`** Notifies the host that the execution is about to enter a region of code in which the effects of a thread abort or unhandled exception affect only the current task. |
| 7 | **`public static void EndThreadAffinity()`** 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)`** 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)`** Retrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields that are marked with the `ThreadStaticAttribute` attribute instead. |
| 10 | **`public static AppDomain GetDomain()`** Returns the current domain in which the current thread is running. |
| 11 | **`public static AppDomain GetDomainID()`** Returns a unique application domain identifier. |
| 12 | **`public static LocalDataStoreSlot GetNamedDataSlot(string name)`** Looks up a named data slot. For better performance, use fields that are marked with the `ThreadStaticAttribute` attribute instead. |
| 13 | **`public void Interrupt()`** Interrupts a thread that is in the `WaitSleepJoin` thread state. |
| 14 | **`public void Join()`** Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage message pumping. This method has different overloads. |
| 15 | **`public static void MemoryBarrier()`** Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses after the `MemoryBarrier` call execute before memory accesses before the `MemoryBarrier` call. |
| 16 | **`public static void ResetAbort()`** Cancels an `Abort` requested for the current thread. |
| 17 | **`public static void SetData(LocalDataStoreSlot slot, Object data)`** Sets the data in the specified slot on the currently running thread, for the current thread's current domain. For better performance, use fields that are marked with the `ThreadStaticAttribute` attribute instead. |
| 18 | **`public void Start()`** Starts a thread. |
| 19 | **`public static void Sleep(int millisecondsTimeout)`** Suspends the thread for a specified time. |
| 20 | **`public static void SpinWait(int iterations)`** Causes the thread to wait for the number of iterations 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 a field value. The value is the latest written by any processor in the computer, regardless of the number of processors or processor cache state. This method has different overloads. Only some forms are given 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 a field immediately, so that the value is visible to all processors in the computer. This method has different overloads. Only some forms are given 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. |
Threads are created by extending the `Thread` class. The extended `Thread` class calls the **`Start()`** method to begin the child thread's execution.
The following program demonstrates this concept:
## Example
```csharp
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
The `Thread` class provides various methods for managing threads.
The following example demonstrates the use of the **`Sleep()`** method for pausing a thread for a specific time.
## Example
```csharp
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
// The thread pauses 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();
}
}
}
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
The **`Abort()`** method is used to destroy a thread.
It aborts a thread at runtime by throwing a **`ThreadAbortException`**. 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
```csharp
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
π Categories
- β‘ JavaScript (1589)
- π PHP (872)
- π Python3 (810)
- π HTML (691)
- βοΈ C# (650)
- π Python (594)
- β Java (552)
- βοΈ PyTorch (534)
- π§ Linux (472)
- βοΈ C (432)
- π¦ jQuery (406)
- π¨ CSS (377)
- π XML (259)
- π¦ jQuery UI (231)
- π― Bootstrap (220)
- βοΈ C++ (215)
- π °οΈ Angular (205)
- π HTML DOM (201)
- π΄ Redis (188)
- π Web Building (142)
- π Vue.js (141)
- π R (131)
- πΌ Pandas (124)
- ποΈ SQL (105)
- βοΈ Docker (86)
- βοΈ TypeScript (73)
- βοΈ Highcharts (70)
- π AI Agent (70)
- βοΈ React (68)
- π Node.js (65)
- βοΈ Machine Learning (60)
- π Git (59)
- π΅ Go (58)
- π Markdown (58)
- π’ NumPy (55)
- π§ͺ Flask (54)
- βοΈ Scala (53)
- ποΈ SQLite (52)
- π JSTL (52)
- βοΈ VS Code (51)
- π MongoDB (49)
- π Perl (48)
- π Ruby (47)
- π Matplotlib (47)
- βοΈ Uncategorized (46)
- π Swift (46)
- ποΈ PostgreSQL (46)
- βοΈ Data Structures (46)
- π Playwright (46)
- π iOS (45)
- ποΈ MySQL (44)
- βοΈ LangChain (43)
- π FastAPI (40)
- βοΈ Ionic (38)
- π Design Patterns (37)
- βοΈ Eclipse (37)
- π¨ CSS3 (34)
- π Lua (34)
- βοΈ Codex (34)
- πΈ Django (32)
- βοΈ OpenCV (32)
- π Rust (31)
- π JSP (31)
- βοΈ Claude Code (31)
- π Pillow (30)
- βοΈ OpenCode (28)
- π AI Skills (27)
- π Flutter (26)
- π Maven (26)
- π¨ Tailwind CSS (25)
- π§ TensorFlow (25)
- π Servlet (24)
- π Dart (23)
- π Assembly (23)
- βοΈ Memcached (22)
- βοΈ SVG (22)
- βοΈ Electron (22)
- π NLP (22)
- π Regex (21)
- π Android (20)
- π£ Kotlin (19)
- π Julia (19)
- π SOAP (17)
- π Selenium (17)
- π PowerShell (17)
- π Sass (16)
- π HTTP (16)
- π Zig (15)
- π AI (15)
- π AJAX (14)
- π Swagger (14)
- βοΈ Scikit-learn (13)
- βοΈ ECharts (13)
- βοΈ Chart.js (13)
- βοΈ Cursor (13)
- βοΈ SciPy (12)
- π RDF (12)
- π Ollama (12)
- π Next.js (12)
- π Plotly Dash (12)
- π JSON (11)
- π RESTful API (11)
- π WSDL (9)
- βοΈ CMake (8)
- π Firebug (7)
- π Nginx (6)
- βΈοΈ Kubernetes (6)
- π Jupyter (6)
- π LaTeX (4)
- π UniApp (4)
- ποΈ SQL Server (1)
YouTip