In C#, a thread stands as the tiniest executable entity within a program, symbolizing an independent flow of execution. Enabling concurrent task execution, threads enhance performance by optimizing CPU utilization. Upon initializing a C# program, the primary thread is automatically spawned by the .NET runtime. Additional threads can be manually created to execute parallel tasks alongside the main routine.
In C#, the Thread class is specified within the System.Threading namespace and is frequently employed for the creation and administration of threads.
Syntax:
It has the following syntax.
Thread t = new Thread (new ThreadStart(MethodName));
t.Start();
When we are using a lambda expression.
Thread t = new Thread(() => {
// thread code here
});
t.Start();
In this structure,
- ThreadStart: This refers to a delegate that directs to a function that will be executed within the newly created thread.
- MethodName: This specifies the identifier of the function that we intend to run.
C# Thread Class Example
Let's consider a scenario to demonstrate the thread class in C#.
Example
using System;
using System.Threading;
class C# Tutorial
{
static void Num()
{
for (int m = 1; m <= 3; m++)
{
Console.WriteLine("Thread " + Thread.CurrentThread.Name + ": " + m);
Thread.Sleep(500); // Pause for 0.5 seconds
}
}
static void Main()
{
Thread m1 = new Thread(Num);
m1.Name = "Worker";
m1.Start(); // Start the thread
m1.Join(); // Wait until m1 finishes
Console.WriteLine("Thread finished. Main thread exiting.");
}
}
Output:
Thread Worker: 1
Thread Worker: 2
Thread Worker: 3
Thread finished. Main thread exiting.
Explanation:
In this instance, we've established a thread to carry out a function called Num. The Num function displays numbers from 1 to 3, introducing a brief delay after each cycle. Within the primary function, we instantiate m1 and invoke the Start function. Subsequently, invoking m1.Join guarantees that the primary thread pauses until the secondary thread finishes its task, allowing the final message to be displayed.
Key Features of the C# Thread Class
There are several features of the Thread class in C#. Some main features are as follows:
- It is defined in the System.Threading namespace.
- It defines a single thread of execution.
- A thread may be created using a delegate. It can be either with a method reference or a lambda expression.
- A thread in C# supports foreground and background modes.
- It offers several properties, including Priority, Name, IsAlive, and methods like Abort, Start, Sleep, and Join.
Properties and Methods of the Thread Class
Here is a compilation of the frequently used attributes of the thread class in C#. These include:
| Property | Description |
|---|---|
| IsAlive | It returns true if the thread is still running; otherwise, it returns false. |
| CurrentContext | It gets the current context in which the thread is running. |
| CurrentCulture | It is commonly utilized to get or set for the current thread. |
| CurrentPrinciple | The Thread.CurrentPrincipal property gets or sets the security principal for the current method. |
| CurrentThread | The Thread.CurrentThread property gets the reference to the currently executing thread. |
| CurrentUICulture | The Thread.CurrentUICulture property is used to get or set the current UI culture, which uses the resource manager to look up culture-specific resources at runtime. |
| ThreadState | The Thread.ThreadState property is utilized to get a value that shows the current state of the thread. |
| Priority | The Thread.Priority property is commonly utilized to get or set a value that indicates the scheduling priority of the thread. |
| IsThreadPoolThread | The Thread.ThreadPoolThread property is used to read a property that specifies whether a thread belongs to the .Net thread pool. |
| IsBackground | The Thread.IsBackground property is commonly utilized to get or set a value that specifies whether a thread is a background thread. |
| ManagedThreadId | The Thread.ManagedThreadId property is used to get a unique identifier for the current managed thread. |
Name |
The Thread.Name property is commonly utilized to get or set the thread name. |
| ExecutionContext | The Thread.ExecutionContext is used to get an ExecutionContext object that holds information about the different contexts associated with the current thread. |
C# Thread Class Property Example
Let's consider an example to demonstrate the characteristics of threads in C#.
Example
using System;
using System.Threading;
class C# Tutorial
{
static void TechTask()
{
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("Executing Thread " + Thread.CurrentThread.Name + ": Step " + i);
Thread.Sleep(500);
}
}
static void Main()
{
Thread m1 = new Thread(TechTask);
m1.Name = "WorkerThread";
m1.Priority = ThreadPriority.Highest;
m1.IsBackground = true;
Console.WriteLine("Thread Details - Name: " + m1.Name +
", Priority: " + m1.Priority +
", Background: " + m1.IsBackground);
m1.Start();
m1.Join();
Console.WriteLine("Is the thread still running? " + m1.IsAlive);
}
}
Output:
Thread Details - Name: WorkerThread, Priority: Highest, Background: True
Executing Thread WorkerThread: Step 1
Executing Thread WorkerThread: Step 2
Executing Thread WorkerThread: Step 3
Is the thread still running? False
Explanation:
In this illustration, we showcase the process of establishing and overseeing a thread through the application of the C# Thread class. Initially, a worker thread (m1) is generated to execute the TechTask method, assigned a name, set to the highest priority, and designated as a background thread. Subsequently, the initiation of execution is triggered by invoking the Start method, followed by the utilization of the Join function to prompt the main thread to pause until the worker thread completes its task. Ultimately, the IsAlive function is employed to verify if the thread is currently active.
Thread Class Methods
The subsequent table demonstrates the functions of the Thread class in C#.
| Method | Description |
|---|---|
| Abort() | It is used to terminate the thread. It raises ThreadAbortException. |
| Interrupt() | It is used to interrupt a thread that is in theWaitSleepJoinstate. |
| Join() | It is used to block all the calling threads until this thread terminates. |
| ResetAbort() | It is used to cancel the Abort request for the current thread. |
| Resume() | It is used to resume the suspended thread. It is obsolete. |
| Sleep(Int32) | It is used to suspend the current thread for the specified milliseconds. |
| Start() | It changes the current state of the thread to Runnable. |
| Suspend() | It suspends the current thread if it is not suspended. It is obsolete. |
| Yield() | It is used to yield the execution of the current thread to another thread. |
C# Thread Methods Example using Thread Start, Sleep, and Join
Let's consider a scenario to demonstrate the implementation of the Thread Start, Sleep, and Join functions in C#.
Example
using System;
using System.Threading;
class C# Tutorial
{
static void Number()
{
for (int m = 1; m <= 5; m++)
{
Console.WriteLine("Thread: Printing number " + m);
Thread.Sleep(500);
}
}
static void Main()
{
// Create an instance of thread
Thread m1 = new Thread(Number);
Console.WriteLine("Main thread starting m1...");
m1.Start(); // Start the thread
// Wait for m1 to finish
m1.Join();
Console.WriteLine("m1 has completed \nThe main threads ends here.");
}
}
Output:
Main thread starting m1...
Thread: Printing number 1
Thread: Printing number 2
Thread: Printing number 3
Thread: Printing number 4
Thread: Printing number 5
m1 has completed
The main threads ends here.
Explanation:
In this illustration, we've initiated a thread to execute the Number function, displaying numbers from 1 to 5 after a brief pause. Within the primary function, we instantiate m1 and invoke the Start function, followed by m1.Join method which guarantees the primary thread pauses until the auxiliary thread finishes its tasks prior to outputting the concluding statement.
Thread Class Constructor in C#
In C#, the Thread class constructor offers four different constructors as outlined below.
1) Thread(ThreadStart start)
It represents the constructor of the Thread class in C#. This method sets up a fresh thread to run a specified method. It requires a ThreadStart delegate to identify the methods to run on the newly created thread.
2) Thread(ParameterizedThreadStart start)
The Thread(ParameterizedThreadStart start) method in C# creates a fresh Thread class object. It designates a delegate to allow an object to be transmitted to the thread during its commencement of execution.
It serves as a delegate indicating the method to run upon the thread's initiation. An ArgumentNullException is thrown if the start parameter is empty.
3) Thread(ThreadStart start, int maxStackSize)
In C#, when using the Thread(ThreadStart start, int maxStackSize) constructor, a new object of the Thread class is created with a specified maximum stack size for the thread.
It is a ThreadStart delegate that specifies the actions to be performed when the thread begins execution.
maxStackSize: This parameter specifies the utmost stack size allocated for the thread. To utilize the default maximum stack size specified in the header for the executable, we should input 0.
4) Instantiate a new thread with a specified starting method using the Thread class constructor that accepts a ParameterizedThreadStart delegate and an integer value for the maximum stack size.
This method initializes the thread class, providing the capability to pass an object to the thread through a ParameterizedThreadStart delegate. It also sets the maximum stack size for the thread.
Advantages of the Thread Class in C#
There are several advantages of the thread class in C#. Some of them are as follows:
- It is used to keep UI responsive for applications while background tasks are running.
- It has better CPU utilization while developing applications.
- It enables parallel execution that helps to perform multiple tasks at the same time.
- It helps to improve the application performance.
Disadvantages of the Thread Class in C#
There are several disadvantages of the Thread Class in C#. Some main disadvantages are as follows:
- It is very complex to handle.
- It has some synchronization issues, such as race conditions and deadlocks.
- It uses higher memory that contains several threads.
Conclusion
In summary, the C# Thread class plays a vital role in executing numerous tasks concurrently. This class empowers developers to generate, initiate, pause, resume, and terminate threads, thereby enhancing system performance through efficient CPU utilization. With a range of properties and methods, it effectively manages various thread operations.
C# Thread Class FAQs
1) What is a thread class in C#?
In C#, a thread serves as the tiniest unit of execution within a program, embodying an independent flow of execution. This functionality facilitates concurrent operations, enhancing overall performance through more efficient CPU utilization.
2) How do we create a thread in C#?
We can instantiate a thread by using the thread constructor and providing the method as an argument.
Thread t = new Thread(new ThreadStart(MethodName));
t.Start();
3) Is it possible to initiate a thread again after it has completed its execution?
No, after a thread has finished its execution, it is not possible to restart it. To rerun the code, a new Thread object must be instantiated.
4) What is the Thread.Abort method?
The Thread.Abort function is frequently used to end the execution of a thread by raising a ThreadAbortException.
The primary distinction lies in how they handle asynchronous operations.
The Thread.Sleep(milliseconds) method halts the execution of the current thread for the duration specified in milliseconds, causing it to enter a blocked state for that period.
Using Task.Delay(milliseconds) initiates a non-blocking delay operation that enables concurrent execution of other tasks. This feature ensures that the thread remains unblocked during the asynchronous delay.