Open In App

C# Thread Class

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, multi-threading is implemented using the Thread class, which is part of the System.Threading namespace. This class allows for the creation, management, and control of threads within an application. The Thread class provides various methods and properties to handle thread execution, prioritize tasks, and manage thread states.

  • The Thread class allows the creation of both foreground and background threads.
  • It allows the setting and getting of thread priorities.
  • It provides properties to check the current state of a thread.
  • We can retrieve the reference to the currently executing thread.
  • The Thread class is sealed, meaning it cannot be inherited.
  • Through the Thread class, we can manage thread execution, interruption, and joining.

Example: Illustration of Creating a thread using Thread Class in C#.

C#
// Illusraion of Creating
// thread using Thread class in C#
using System;
using System.Threading;

class Geeks
{
	public static void Main(string[] args)
	{
		// Create a new thread
		Thread t1 = new Thread(new ThreadStart(task));
      
		// Start the thread
		t1.Start();

		Console.WriteLine("Main thread...");
	}
	public static void task()
	{
		Console.WriteLine("Thread is running....");
	}
}

Output
Main thread...
Thread is running....

Note: When we are creating multithreaded program we need to synchronized the threads. The Thread synchronization ensures safe access to shared resources by multiple threads. We can use lock, Monitor, Mutex, or Semaphore to prevent unwanted behaviour like race conditions.

Constructor

Constructors

Description

Thread(ParameterizedThreadStart)

Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started.

Thread(ParameterizedThreadStart, Int32)

Creates a new Thread instance with a delegate for object passing and sets the maximum stack size

Thread(ThreadStart)

Initializes a new instance of the Thread class

Thread(ThreadStart, Int32)

Initializes a new instance of the Thread class, specifying the maximum stack size for the thread.

Example: Demonstration of Using the Thread Class with Constructor

C#
// C# program to illustrate
// ThreadStart constructor
using System;
using System.Threading;

public class Geeks
{
	public static void Main()
	{
		// Creating and initializing thread
		// Using thread class and 
		// ThreadStart constructor
		Thread t = new Thread(new ThreadStart(task));
		t.Start();
	}
  
    public static void task()
	{		for (int j = 0; j < 2; j++)
		{
			Console.WriteLine("My Thread is" +
			" in progress...!!");
		}
	}
}

Output
My Thread is in progress...!!
My Thread is in progress...!!

Properties

Properties

Description

ApartmentState

Gets or sets the apartment state of this thread.

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 or not a thread is a background thread.

IsThreadPoolThread

Gets a value indicating whether or not a thread belongs to the managed thread pool.

ManagedThreadId

Gets a unique identifier for the currently 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.

Example:

C#
// C# program to illustrate how to
// set and get the priority of threads
using System;
using System.Threading;

class Geeks
{
	static public void Main()
	{
		// Creating and initializing threads
		Thread t1 = new Thread(work);
		Thread t2 = new Thread(work);
		Thread t3 = new Thread(work);

		// Set the priority of threads
		t2.Priority = ThreadPriority.Lowest;
		t3.Priority = ThreadPriority.AboveNormal;
		t1.Start();
		t2.Start();
		t3.Start();

		// Display the priority of threads
		Console.WriteLine("The priority of Thread 1 is: {0}",
		t1.Priority);

		Console.WriteLine("The priority of Thread 2 is: {0}",
		t2.Priority);

		Console.WriteLine("The priority of Thread 3 is: {0}",
		t3.Priority);
	}

	public static void work()
	{
		// Sleep for 100 milliseconds
		Thread.Sleep(100);
	}
}

Output
The priority of Thread 1 is: Normal
The priority of Thread 2 is: Lowest
The priority of Thread 3 is: AboveNormal

Methods

Methods

Description

Abort()

Used to terminate the thread.

AllocateDataSlot()

Allocates an unnamed data slot on all the threads.

AllocateNamedDataSlot(String)

Allocates a named data slot on all threads.

BeginCriticalRegion()

Alerts a host that code execution is entering a region where thread aborts or unhandled exceptions could impact other tasks in the application domain.

BeginThreadAffinity()

Notifies about executing instructions that depend on the identity of the current physical operating system thread.

DisableComObjectEagerCleanup()

Turns off automatic cleanup of runtime callable wrappers (RCW) for the current thread.

EndCriticalRegion()

Notify the execution entering a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.

EndThreadAffinity()

Notify the executing instructions that depend on the identity of the current physical operating system thread.

Equals(Object)

Determines whether the specified object is equal to the current object.

Finalize()

Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object.

FreeNamedDataSlot(String)

Eliminates the association between a name and a slot, for all threads in the process.

GetApartmentState()

Returns an ApartmentState value indicating the apartment state.

GetCompressedStack()

Returns a CompressedStack object that can be used to capture the stack for the current thread.

GetData(LocalDataStoreSlot)

Retrieves the value from the specified slot on the current thread, within the current thread’s current domain.

GetDomain()

Returns the current domain in which the current thread is running.

GetDomainID()

Returns a unique application domain identifier.

GetHashCode()

Returns a hash code for the current thread.

GetNamedDataSlot(String)

Looks up a named data slot.

GetType()

Gets the Type of the current instance.

Interrupt()

Interrupts a thread that is in the WaitSleepJoin thread state.

Join()

Blocks the calling thread until this instance’s thread terminates, while handling COM and SendMessage.

MemberwiseClone()

Creates a shallow copy of the current Object.

MemoryBarrier()

Ensures proper ordering of memory operations across threads, preventing the compiler or runtime from reordering

ResetAbort()

Cancels an Abort(Object) requested for the current thread.

Resume()

Resumes a thread that has been suspended.

SetApartmentState(ApartmentState)

Sets the apartment state of a thread before it is started.

SetCompressedStack(CompressedStack)

Applies a captured CompressedStack to the current thread.

SetData(LocalDataStoreSlot, Object)

Sets the data in the specified slot on the currently running thread, for that thread’s current domain.

Sleep()

Suspends the current thread for the specified amount of time.

SpinWait(Int32)

Causes a thread to wait the number of times defined by the iterations parameter.

Start()

Causes a thread to be scheduled for execution.

Suspend()

Either suspends the thread, or if the thread is already suspended, has no effect.

ToString()

Returns a string that represents the current object.

VolatileRead()

Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of the processor cache.

VolatileWrite()

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

Yield()

Yields execution from the calling thread to another ready thread on the processor. The OS selects the thread.

Important Points:

  • For better performance, use fields marked with the ThreadStaticAttribute instead of relying on methods like MemoryBarrier() and GetDate() etc.
  • Avoid using Thread.Abort() because it forcibly terminates a thread, which can lead to unpredictable behavior, such as leaving shared resources in an inconsistent state or causing memory leaks. and it is used in older version now it is deprecated, In newer versions we can use cooperative cancellation techniques like CancellationToken.

Example:

C#
// Illusraion of Creating
// thread using Thread class in C#
using System;
using System.Threading;

class Geeks
{
	public static void Main(string[] args)
	{
		// Create a new thread
		Thread thread = new Thread(new ThreadStart(task));
      
		// Start the thread
		thread.Start();

		Console.WriteLine("Main thread is exiting.");
	}
	public static void task()
	{
		Console.WriteLine("Thread is running.");
	}
	public static void work()
	{
		// Sleep for 100 ms
		Thread.Sleep(100);
	}
}

Output
Main thread is exiting.
Thread is running.


Next Article

Similar Reads