top

Search

C# Tutorial

Multithreading is a method to implement concurrent programming where multiple threads operate simultaneously. Threads are lightweight processes that signify the execution path in a program. Thread usage increases the efficiency of an application and reduces the CPU cycle time wastage.The Thread Life CycleThe thread life cycle encapsulates the life of a thread. It starts when an object of System.Threading.Thread class is created and ends when thread has terminated. The thread states in the thread life cycle are given as follows:1. Unstarted StateWhen the instance of the thread has been created but the Start method has not been called, that is the unstarted state.2. Ready StateWhen the thread is ready to run, it is in the ready state. This thread is just waiting for the CPU cycle.3. Not runnable StateA thread can be in the not runnable state when the wait or sleep method has been called. This state can also occur if the thread is blocked because of I/O operations.4. Dead StateThe thread enters the dead state if it is aborted or if it has completed its execution.Structure of MultithreadingMultithreading in C# involves running multiple threads concurrently within a single program, enhancing performance and efficiency. Here are the key components:Namespace: The System.Threading namespace provides classes and methods to create and manage threadsThread Class: A thread in C# is represented by the Thread class, where each thread executes a separate path of codeStart Method: The Thread.Start method initiates a thread's executionSynchronization Mechanisms: Synchronization is crucial in multithreading to prevent data inconsistencies and race conditions, and C# provides mechanisms like locks, mutexes, and semaphores to manage access to shared resourcesExample:Thread thread = new Thread(new ThreadStart(TaskMethod)); thread.Start();When and How to Use Multithreading in C#?Multithreading in C# is beneficial when tasks are independent and can run concurrently, such as in CPU-bound operations,I/O-bound tasksMaintaining application responsiveness during lengthy processes.Consider an example of web server, when a web server receives multiple HTTP requests simultaneously, it can use multithreading to handle each request in a separate thread. This ensures that a slow request (e.g., a request that requires a database query) does not block other requestsUsing multithreading in C# can significantly improve application performance and user experienceHow to Use Multithreading:To implement multithreading, start by creating a new thread using the Thread class from the System.Threading namespace. Define the task to be executed in a method and pass this method as a ThreadStart delegate to the Thread constructor. Invoke the Start method to run the thread. For example, Thread thread = new Thread(new ThreadStart(TaskMethod)); thread.Start();. Advanced methods include using the Task Parallel Library (TPL) and async and await keywords for simpler and more efficient multithreading management. Always ensure proper synchronization to avoid race conditions and deadlocks. Multithreading in C# should be used judiciously, keeping in mind the complexity it introduces to debugging and maintenance.Steps to use Multithreading in c#1. Creating a Thread:Thread thread = new Thread(new ThreadStart(TaskMethod));  thread.Start();2. Using Task Parallel Library (TPL): Task.Run(() => TaskMethod());3. Async/Await for Asynchronous Programming:async Task MethodAsync() {  await Task.Run(() => TaskMethod());  }C# Multithreading Best PracticesBest Practices for Multithreading in C#:Prefer Task Parallel Library (TPL): Simplifies thread management and improves efficiency.Use Async/Await: Enhances code readability and maintainability by avoiding callback hell.Proper Synchronization: Use locks, mutexes, and semaphores to manage shared resources and prevent race conditions.Avoid Excessive Locking: Prevents deadlocks and ensures better performance.Thread-Safe Collections: Utilize `System.Collections.Concurrent` for safe handling of collections in a multithreaded environment.Keep Tasks Small: Break down tasks to maximize concurrency and improve performance.Handle Exceptions: Implement proper exception handling within threads to ensure robustness.Limit Thread Creation: Avoid creating too many threads to prevent resource exhaustion.Regular testing and profiling are essential to identify and resolve issues in multithreaded applications..Example Program on MultithreadingHere's a simple example demonstrating multithreading in C#:using System; using System.Threading; class Program {  static void Main() {  Thread thread1 = new Thread(PrintNumbers);  Thread thread2 = new Thread(PrintNumbers);  thread1.Start();  thread2.Start();  thread1.Join();  thread2.Join();  }  static void PrintNumbers() {  for (int i = 0; i < 5; i++) {  Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: {i}");  Thread.Sleep(500); // Simulate work  }  } }Explanation:- Namespace Imports: Includes `System` and `System.Threading`.- Main Method: - Thread Creation: Creates two new threads (`thread1` and `thread2`) with the `PrintNumbers` method as their target. - Start Threads: Initiates both threads using `Start()` method. - Join Threads: Waits for both threads to complete using `Join()` method, ensuring the main thread does not exit prematurely.- PrintNumbers Method: - Loop Execution: Iterates five times, printing the thread ID and loop counter. - Thread.Sleep(500): Simulates work by pausing execution for 500 milliseconds between iterations.This example shows how two threads execute the same method concurrently, improving performance.The Thread ClassThe System.Threading namespace provides the classes and interfaces that implement multithreaded programming. One of the classes in this namespace is the Thread class. This class is used for creating and controlling threads.Details about the constructors, properties and methods in Thread Class are given as follows:Constructors in Thread ClassThe different constructors and their description is given as follows:Table: Constructors in Thread Class in C#Source: MSDNConstructorsDescriptionThread(ParameterizedThreadStart)This constructor 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)This constructor 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)This constructor initializes a new instance of the Thread class.Thread(ThreadStart, Int32)This constructor initializes a new instance of the Thread class, specifying the maximum stack size for the thread.Properties in Thread ClassThe different properties and their description is given as follows:Table: Properties in Thread Class in C#Source: MSDNPropertiesDescriptionApartmentStateThis property gets or sets the apartment state of this thread.CurrentContextThis property gets the current context in which the thread is executing.CurrentCultureThis property gets or sets the culture for the current thread.CurrentPrincipalThis property gets or sets the thread's current principal (for role-based security).CurrentThreadThis property gets the currently running thread.CurrentUICultureThis property gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.ExecutionContextThis property gets an ExecutionContext object that contains information about the various contexts of the current thread.IsAliveThis property gets a value indicating the execution status of the current thread.IsBackgroundThis property gets or sets a value indicating whether or not a thread is a background thread.IsThreadPoolThreadThis property gets a value indicating whether or not a thread belongs to the managed thread pool.ManagedThreadIdThis property gets a unique identifier for the current managed thread.NameThis property gets or sets the name of the thread.PriorityThis property gets or sets a value indicating the scheduling priority of a thread.ThreadStateThis property gets a value containing the states of the current thread.Methods in Thread ClassThe different methods and their description is given as follows:Table: Methods in Thread Class in C#Source: MSDNMethodsDescriptionAbort()This method 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.BeginCriticalRegion()This method 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()This method notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.EndCriticalRegion()This method 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()This method notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.Finalize()This method ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object.GetDomain()This method returns the current domain in which the current thread is running.GetType()This method gets the Type of the current instance.Interrupt()This method interrupts a thread that is in the WaitSleepJoin thread state.MemoryBarrier()This method 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().Resume()This method resumes a thread that has been suspended.Sleep(Int32)This method suspends the current thread for the specified number of milliseconds.Start()This method causes the operating system to change the state of the current instance to Running.Suspend()This method either suspends the thread, or if the thread is already suspended, has no effectVolatileRead(Byte)This method 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(Byte, Byte)This method writes a value to a field immediately, so that the value is visible to all processors in the computer.Yield()This method 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 toCreate a ThreadTo create a Thread, simply use the Thread class:Source Code: Program to create a Thread in C#using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; class Example {    public void FirstThread()    {        for (int i = 0; i < 5; i++)        {            Console.WriteLine("My Thread");        }    } } class Sample {    public static void Main()    {        Example e = new Example();        Thread t = new Thread(new ThreadStart(e.FirstThread));        t.Start();        Console.Read();    } }The above program generates the following output:My Thread My Thread My Thread My Thread My ThreadThe Main ThreadThe Main Thread is the first thread that is created and executed inside a process. It is automatically created when the process starts execution.A program that demonstrates the Main thread is given as follows:Source Code: Program to implement Main Thread in C#using System; using System.Threading; namespace MultithreadingDemo {   class Example   {      static void Main(string[] args)      {         Thread myThread = Thread.CurrentThread;         myThread.Name = "Main_Thread";         Console.WriteLine("This thread is the {0}", myThread.Name);      }   } }The output of the above program is as follows:This thread is the Main_ThreadNow let us understand the above program.The CurrentThread property of the Thread class is used to access the Main thread. The name of the thread is specified is Main_Thread. After that, this is displayed. The code snippet for this is given as follows:    Thread myThread = Thread.CurrentThread;         myThread.Name = "Main_Thread";         Console.WriteLine("This thread is the {0}", myThread.Name);Check status of Current ThreadThe isAlive property is to be used if you want to check the status of current Thread in C#.Let us see an example:Source Code: Program to check the status of current Thread in C#using System; using System.Threading; namespace Example {    class MyThread    {        static void Main(string[] args)        {            Thread t = Thread.CurrentThread;            t.Name = "This is my first thread!";            Console.WriteLine("Status of current thread = {0}", t.IsAlive);            Console.ReadKey();        }    } }The above program generates the following output:Status of current thread = TrueGet the name of Current ThreadTo get the name of the current thread, you need to use the Name property of the Thread class. Let us see an example:Source Code: Program to get the name of current Thread in C#using System; using System.Threading; namespace Demo {    class MyClass    {        static void Main(string[] args)        {            Thread t = Thread.CurrentThread;            t.Name = "First Thread";            Console.WriteLine("Name of thread : {0}", t.Name);            Console.ReadKey();        }    } }The above program generates the following output:Name of thread : First ThreadDisplay the priority of the Current ThreadThe Priority property of the Thread class is to be used for displaying the priority of the Current Thread:Source Code: Program to display the priority of current Thread in C#using System; using System.Threading; namespace Example {    class MyThreadClass    {        static void Main(string[] args)        {            Thread t = Thread.CurrentThread;            t.Name = "First Thread";            Console.WriteLine("Thread Name : {0}", t.Name);            Console.WriteLine("Thread Priority : {0}", t.Priority);            Console.ReadKey();        }    } }The above program generates the following output:Thread Name : First Thread Thread Priority : NormalPause the Thread for a specified periodUse the Sleep() method to pause the Thread for a specified period. Let us see the code now:Source Code: Program to pause the Thread for a specified period in C#using System; using System.Threading; namespace Example {    class MyThreadClass    {        static void Main(string[] args)        {            Thread t = Thread.CurrentThread;            t.Name = "First Thread";            Console.WriteLine("Thread Name : {0}", t.Name);            Console.WriteLine("Thread Priority : {0}", t.Priority);            Console.WriteLine("Child Thread Paused...");            // using Sleep() method            Thread.Sleep(1000);            Console.WriteLine("Child Thread Resumed...");            Console.ReadKey();        }    } }The above program generates the following output:Thread Name : First Thread Thread Priority : Normal Child Thread Paused... Child Thread Resumed...ConclusionMultithreading in C# significantly enhances application performance and responsiveness by executing tasks concurrently. Proper implementation and adherence to best practices, including synchronization and efficient use of TPL and async/await, are crucial. By leveraging multithreading, developers can create scalable, responsive applications. However, it's essential to manage the complexity and potential issues associated with concurrent execution. Regular testing and profiling ensure smooth and efficient performance.
logo

C# Tutorial

Multithreading in C#

Multithreading is a method to implement concurrent programming where multiple threads operate simultaneously. Threads are lightweight processes that signify the execution path in a program. Thread usage increases the efficiency of an application and reduces the CPU cycle time wastage.

The Thread Life Cycle

The thread life cycle encapsulates the life of a thread. It starts when an object of System.Threading.Thread class is created and ends when thread has terminated. The thread states in the thread life cycle are given as follows:

1. Unstarted State

When the instance of the thread has been created but the Start method has not been called, that is the unstarted state.

2. Ready State

When the thread is ready to run, it is in the ready state. This thread is just waiting for the CPU cycle.

3. Not runnable State

A thread can be in the not runnable state when the wait or sleep method has been called. This state can also occur if the thread is blocked because of I/O operations.

4. Dead State

The thread enters the dead state if it is aborted or if it has completed its execution.

Structure of Multithreading

Multithreading in C# involves running multiple threads concurrently within a single program, enhancing performance and efficiency. Here are the key components:

  • Namespace: The System.Threading namespace provides classes and methods to create and manage threads
  • Thread Class: A thread in C# is represented by the Thread class, where each thread executes a separate path of code
  • Start Method: The Thread.Start method initiates a thread's execution
  • Synchronization Mechanisms: Synchronization is crucial in multithreading to prevent data inconsistencies and race conditions, and C# provides mechanisms like locks, mutexes, and semaphores to manage access to shared resources

Example:

Thread thread = new Thread(new ThreadStart(TaskMethod));
thread.Start();

When and How to Use Multithreading in C#?

Multithreading in C# is beneficial when tasks are independent and can run concurrently, such as in 

  • CPU-bound operations,
  • I/O-bound tasks
  • Maintaining application responsiveness during lengthy processes.

Consider an example of web server, when a web server receives multiple HTTP requests simultaneously, it can use multithreading to handle each request in a separate thread. This ensures that a slow request (e.g., a request that requires a database query) does not block other requests

Using multithreading in C# can significantly improve application performance and user experience

How to Use Multithreading:

To implement multithreading, start by creating a new thread using the Thread class from the System.Threading namespace. Define the task to be executed in a method and pass this method as a ThreadStart delegate to the Thread constructor. Invoke the Start method to run the thread. For example, Thread thread = new Thread(new ThreadStart(TaskMethod)); thread.Start();. Advanced methods include using the Task Parallel Library (TPL) and async and await keywords for simpler and more efficient multithreading management. Always ensure proper synchronization to avoid race conditions and deadlocks. Multithreading in C# should be used judiciously, keeping in mind the complexity it introduces to debugging and maintenance.

Steps to use Multithreading in c#

1. Creating a Thread:

Thread thread = new Thread(new ThreadStart(TaskMethod));
 thread.Start();

2. Using Task Parallel Library (TPL):

 Task.Run(() => TaskMethod());

3. Async/Await for Asynchronous Programming:

async Task MethodAsync() {
 await Task.Run(() => TaskMethod());
 }

C# Multithreading Best Practices

Best Practices for Multithreading in C#:

  • Prefer Task Parallel Library (TPL): Simplifies thread management and improves efficiency.
  • Use Async/Await: Enhances code readability and maintainability by avoiding callback hell.
  • Proper Synchronization: Use locks, mutexes, and semaphores to manage shared resources and prevent race conditions.
  • Avoid Excessive Locking: Prevents deadlocks and ensures better performance.
  • Thread-Safe Collections: Utilize `System.Collections.Concurrent` for safe handling of collections in a multithreaded environment.
  • Keep Tasks Small: Break down tasks to maximize concurrency and improve performance.
  • Handle Exceptions: Implement proper exception handling within threads to ensure robustness.
  • Limit Thread Creation: Avoid creating too many threads to prevent resource exhaustion.

Regular testing and profiling are essential to identify and resolve issues in multithreaded applications..

Example Program on Multithreading

Here's a simple example demonstrating multithreading in C#:

using System;
using System.Threading;
class Program {
 static void Main() {
 Thread thread1 = new Thread(PrintNumbers);
 Thread thread2 = new Thread(PrintNumbers);
 thread1.Start();
 thread2.Start();
 thread1.Join();
 thread2.Join();
 }
 static void PrintNumbers() {
 for (int i = 0; i < 5; i++) {
 Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: {i}");
 Thread.Sleep(500); // Simulate work
 }
 }
}

Explanation:

- Namespace Imports: Includes `System` and `System.Threading`.

- Main Method:

 - Thread Creation: Creates two new threads (`thread1` and `thread2`) with the `PrintNumbers` method as their target.

 - Start Threads: Initiates both threads using `Start()` method.

 - Join Threads: Waits for both threads to complete using `Join()` method, ensuring the main thread does not exit prematurely.

- PrintNumbers Method:

 - Loop Execution: Iterates five times, printing the thread ID and loop counter.

 - Thread.Sleep(500): Simulates work by pausing execution for 500 milliseconds between iterations.

This example shows how two threads execute the same method concurrently, improving performance.

The Thread Class

The System.Threading namespace provides the classes and interfaces that implement multithreaded programming. One of the classes in this namespace is the Thread class. This class is used for creating and controlling threads.

Details about the constructors, properties and methods in Thread Class are given as follows:

Constructors in Thread Class

The different constructors and their description is given as follows:

Table: Constructors in Thread Class in C#

Source: MSDN

ConstructorsDescription
Thread(ParameterizedThreadStart)This constructor 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)This constructor 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)This constructor initializes a new instance of the Thread class.
Thread(ThreadStart, Int32)This constructor initializes a new instance of the Thread class, specifying the maximum stack size for the thread.

Properties in Thread Class

The different properties and their description is given as follows:

Table: Properties in Thread Class in C#

Source: MSDN

PropertiesDescription
ApartmentStateThis property gets or sets the apartment state of this thread.
CurrentContextThis property gets the current context in which the thread is executing.
CurrentCultureThis property gets or sets the culture for the current thread.
CurrentPrincipalThis property gets or sets the thread's current principal (for role-based security).
CurrentThreadThis property gets the currently running thread.
CurrentUICultureThis property gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.
ExecutionContextThis property gets an ExecutionContext object that contains information about the various contexts of the current thread.
IsAliveThis property gets a value indicating the execution status of the current thread.
IsBackgroundThis property gets or sets a value indicating whether or not a thread is a background thread.
IsThreadPoolThreadThis property gets a value indicating whether or not a thread belongs to the managed thread pool.
ManagedThreadIdThis property gets a unique identifier for the current managed thread.
NameThis property gets or sets the name of the thread.
PriorityThis property gets or sets a value indicating the scheduling priority of a thread.
ThreadStateThis property gets a value containing the states of the current thread.

Methods in Thread Class

The different methods and their description is given as follows:

Table: Methods in Thread Class in C#

Source: MSDN

MethodsDescription
Abort()This method 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.
BeginCriticalRegion()This method 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()This method notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.
EndCriticalRegion()This method 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()This method notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.
Finalize()This method ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object.
GetDomain()This method returns the current domain in which the current thread is running.
GetType()This method gets the Type of the current instance.
Interrupt()This method interrupts a thread that is in the WaitSleepJoin thread state.
MemoryBarrier()This method 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().
Resume()This method resumes a thread that has been suspended.
Sleep(Int32)This method suspends the current thread for the specified number of milliseconds.
Start()This method causes the operating system to change the state of the current instance to Running.
Suspend()This method either suspends the thread, or if the thread is already suspended, has no effect
VolatileRead(Byte)This method 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(Byte, Byte)This method writes a value to a field immediately, so that the value is visible to all processors in the computer.
Yield()This method 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

Create a Thread

To create a Thread, simply use the Thread class:

Source Code: Program to create a Thread in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
class Example
{
   public void FirstThread()
   {
       for (int i = 0; i < 5; i++)
       {
           Console.WriteLine("My Thread");
       }
   }
}
class Sample
{
   public static void Main()
   {
       Example e = new Example();
       Thread t = new Thread(new ThreadStart(e.FirstThread));
       t.Start();
       Console.Read();
   }
}

The above program generates the following output:

My Thread
My Thread
My Thread
My Thread
My Thread

The Main Thread

The Main Thread is the first thread that is created and executed inside a process. It is automatically created when the process starts execution.

A program that demonstrates the Main thread is given as follows:

Source Code: Program to implement Main Thread in C#

using System;
using System.Threading;
namespace MultithreadingDemo
{
  class Example
  {
     static void Main(string[] args)
     {
        Thread myThread = Thread.CurrentThread;
        myThread.Name = "Main_Thread";
        Console.WriteLine("This thread is the {0}", myThread.Name);
     }
  }
}

The output of the above program is as follows:

This thread is the Main_Thread

Now let us understand the above program.

The CurrentThread property of the Thread class is used to access the Main thread. The name of the thread is specified is Main_Thread. After that, this is displayed. The code snippet for this is given as follows:

    Thread myThread = Thread.CurrentThread;
        myThread.Name = "Main_Thread";
        Console.WriteLine("This thread is the {0}", myThread.Name);

Check status of Current Thread

The isAlive property is to be used if you want to check the status of current Thread in C#.

Let us see an example:

Source Code: Program to check the status of current Thread in C#

using System;
using System.Threading;
namespace Example
{
   class MyThread
   {
       static void Main(string[] args)
       {
           Thread t = Thread.CurrentThread;
           t.Name = "This is my first thread!";
           Console.WriteLine("Status of current thread = {0}", t.IsAlive);
           Console.ReadKey();
       }
   }
}

The above program generates the following output:

Status of current thread = True

Get the name of Current Thread

To get the name of the current thread, you need to use the Name property of the Thread class. Let us see an example:

Source Code: Program to get the name of current Thread in C#

using System;
using System.Threading;
namespace Demo
{
   class MyClass
   {
       static void Main(string[] args)
       {
           Thread t = Thread.CurrentThread;
           t.Name = "First Thread";
           Console.WriteLine("Name of thread : {0}", t.Name);
           Console.ReadKey();
       }
   }
}

The above program generates the following output:

Name of thread : First Thread

Display the priority of the Current Thread

The Priority property of the Thread class is to be used for displaying the priority of the Current Thread:

Source Code: Program to display the priority of current Thread in C#

using System;
using System.Threading;
namespace Example
{
   class MyThreadClass
   {
       static void Main(string[] args)
       {
           Thread t = Thread.CurrentThread;
           t.Name = "First Thread";
           Console.WriteLine("Thread Name : {0}", t.Name);
           Console.WriteLine("Thread Priority : {0}", t.Priority);
           Console.ReadKey();
       }
   }
}

The above program generates the following output:

Thread Name : First Thread
Thread Priority : Normal

Pause the Thread for a specified period

Use the Sleep() method to pause the Thread for a specified period. Let us see the code now:

Source Code: Program to pause the Thread for a specified period in C#

using System;
using System.Threading;
namespace Example
{
   class MyThreadClass
   {
       static void Main(string[] args)
       {
           Thread t = Thread.CurrentThread;
           t.Name = "First Thread";
           Console.WriteLine("Thread Name : {0}", t.Name);
           Console.WriteLine("Thread Priority : {0}", t.Priority);
           Console.WriteLine("Child Thread Paused...");
           // using Sleep() method
           Thread.Sleep(1000);
           Console.WriteLine("Child Thread Resumed...");
           Console.ReadKey();
       }
   }
}

The above program generates the following output:

Thread Name : First Thread
Thread Priority : Normal
Child Thread Paused...
Child Thread Resumed...

Conclusion

Multithreading in C# significantly enhances application performance and responsiveness by executing tasks concurrently. Proper implementation and adherence to best practices, including synchronization and efficient use of TPL and async/await, are crucial. By leveraging multithreading, developers can create scalable, responsive applications. However, it's essential to manage the complexity and potential issues associated with concurrent execution. Regular testing and profiling ensure smooth and efficient performance.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

austin faith

Avery good write-up. Please let me know what are the types of C# libraries used for AI development.

kariya arti

very satisfied!!

jean-Francois Michaud

Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).

Kshitiz

Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz

Ed

The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial