Open In App

Thread Class in C#

Improve
Improve
Like Article
Like
Save
Share
Report

.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } 

In C#, a multi-threading system is built upon the Thread class, which encapsulates the execution of threads. This class contains several methods and properties which helps in managing and creating threads and this class is defined under System.Threading namespace. Characteristics of Thread class:

  • Thread class is used to create threads.
  • With the help of Thread class you can create foreground and background thread.
  • Thread class allows you to set the priority of a thread.
  • It also provides you the current state of a thread.
  • It provides the reference of the current executing thread.
  • It is a sealed class, so it cannot be inherited.

Constructors

Constructor 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) 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 and specifying the maximum stack size for the thread.
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: 

CSharp




// C# program to illustrate
// ThreadStart constructor
using System;
using System.Threading;
 
public class MXThread {
 
    // Non-static method
    public void mythr()
    {
        for (int J = 0; J < 2; J++) {
 
            Console.WriteLine("My Thread is"+
                         " in progress...!!");
        }
    }
}
 
// Driver Class
public class GFG {
 
    // Main Method
    public static void Main()
    {
        // Creating object of ExThread class
        MXThread obj = new MXThread();
 
        // Creating and initializing thread
        // Using thread class and
        // ThreadStart constructor
        Thread t = new Thread(new ThreadStart(obj.mythr));
        t.Start();
    }
}


Output:

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

Properties

Property 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 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.

Example: 

CSharp




// C# program to illustrate how to
// set and get the priority of threads
using System;
using System.Threading;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Creating and initializing threads
        Thread THR1 = new Thread(work);
        Thread THR2 = new Thread(work);
        Thread THR3 = new Thread(work);
 
        // Set the priority of threads
        THR2.Priority = ThreadPriority.Lowest;
        THR3.Priority = ThreadPriority.AboveNormal;
        THR1.Start();
        THR2.Start();
        THR3.Start();
 
        // Display the priority of threads
        Console.WriteLine("The priority of Thread 1 is: {0}",
                                              THR1.Priority);
 
        Console.WriteLine("The priority of Thread 2 is: {0}",
                                              THR2.Priority);
 
        Console.WriteLine("The priority of Thread 3 is: {0}",
                                              THR3.Priority);
    }
 
    public static void work()
    {
 
        // Sleep for 1 second
        Thread.Sleep(1000);
    }
}


Output:

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

Methods

Method Description
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.
AllocateDataSlot() Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
AllocateNamedDataSlot(String) Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
BeginCriticalRegion() Notifies a host that 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.
BeginThreadAffinity() Notifies a host that managed code is about to execute 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() Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.
EndThreadAffinity() Notifies a host that managed code has finished 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. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
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. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
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. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
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 the thread represented by this instance terminates, while continuing to perform standard COM and SendMessage pumping.
MemberwiseClone() Creates a shallow copy of the current Object.
MemoryBarrier() Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier() execute after memory accesses that follow the call to MemoryBarrier().
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. For better performance, use fields marked with the ThreadStaticAttribute attribute instead.
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.
TrySetApartmentState(ApartmentState) Sets the apartment state of a thread before it is started.
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 processor cache.
VolatileWrite() Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Yield() Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.

Example: 

CSharp




// C# program to illustrate the
// concept of Join() method
using System;
using System.Threading;
 
public class MYThread {
 
    // Non-Static method
    public void mythr1()
    {
        Console.WriteLine("1st thread is Working..!!");
        Thread.Sleep(100);
    }
 
    // Non-Static method
    public void mythr2()
    {
        Console.WriteLine("2nd thread is Working..!!");
    }
}
 
// Driver Class
public class ThreadExample {
 
    // Main method
    public static void Main()
    {
        // Creating instance of MYThread class
        MYThread obj = new MYThread();
 
        // Creating and initializing threads
        Thread T1 = new Thread(new ThreadStart(obj.mythr1));
        Thread T2 = new Thread(new ThreadStart(obj.mythr2));
        T1.Start();
 
        // Join thread
        T1.Join();
        T2.Start();
    }
}


Output:

1st thread is Working..!!
2nd thread is Working..!!

Reference:



Last Updated : 03 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads