Updated July 7, 2023
Introduction to Multithreading in C#
To understand multithreading in c#, let us first understand what is a thread?
- A thread is a light weight process.
- It is an execution path of a program.
- It is the smallest unit of processing in an operating system.
- Thus, a process can have multiple threads.
So, multithreading is a process that contains multiple threads wherein each thread performs a different activity. It saves time because multiple tasks are being executed at the same time by different threads. It increases CPU utilization and increases the efficiency of an application. This works on the time-sharing concept.
Syntax with Explanation
Thread first_thread_name = new Thread(new ThreadStart(method_to_be_executed1));
Thread second_thread_name = new Thread(new ThreadStart(method_to_be_executed2));
first_thread_name.Start();
second_thread_name.Start();
To create a thread, we need to create an object of Thread class. The Thread class constructor takes reference of ThreadStart. ThreadStart is a delegate that represents a method that needs to be executed when the thread begins execution.
The thread begins execution when Start() method is called.
We can create a thread without using ThreadStart delegate as shown in below syntax:
Thread thread_name = new Thread(method_to_be_executed);
thread_name.Start();
Creating Multithreading in C#
In order to create threads, we need to import the system.Threading namespace. We can create and initialize threads using the Thread class.
Example using Thread Class
Code:
using System;
using System.Threading;
public class MultiThreadingDemo
{
public static void Method1()
{
for (int i = 0; i <= 5; i++)
{
Console.WriteLine("Method1 : {0}", i);
}
}
public static void Method2()
{
for (int i = 0; i <= 5; i++)
{
Console.WriteLine("Method2 : {0}",i);
}
}
public static void Main()
{
// Creating and initializing threads
Thread thread1 = new Thread(Method1);
Thread thread2 = new Thread(Method2);
//beginning thread execution
thread1.Start();
thread2.Start();
}
}
Output:
Example using ThreadStart delegate
Code:
using System;
using System.Threading;
public class MultiThreading
{
public static void Method1()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Method1 : {0}", i);
}
}
public static void Method2()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Method2 : {0}", i);
}
}
}
public class MultithreadingDemo
{
public static void Main()
{
Thread thread1 = new Thread(new ThreadStart(MultiThreading.Method1 ) );
Thread thread2 = new Thread(new ThreadStart(MultiThreading.Method2 ) );
thread1.Start();
thread2.Start();
}
}
Output:
In C#, a program always contains one thread i.e. Main Thread. When we create other threads, it becomes a multithreading program and in C# multithreading, there are two types of threads:
- Foreground Thread: This thread keeps executing until it finishes its work even if the main thread terminates.
- Background Thread: When Main Thread terminates, background thread also stops executing and terminates with the main thread.
Methods with Examples
Let us see some commonly used methods of Thread class with examples.
- Sleep(): Used to pause execution of the current thread for a specified period of time, so that other threads begin execution.
Example:
using System;
using System.Threading;
public class Multithreading
{
public void Display()
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
//suspending execution of current thread for 100 milliseconds
Thread.Sleep(100);
}
}
}
public class MultithreadingDemo
{
public static void Main()
{
Multithreading multithreading = new Multithreading();
Thread thread1 = new Thread(new ThreadStart(multithreading.Display));
Thread thread2 = new Thread(new ThreadStart(multithreading.Display));
thread1.Start();
thread2.Start();
}
}
Output:
The output shows that both the threads executed in parallel.
- Abort(): Used to terminate the thread or we can say it is used to stop the execution of the thread permanently.
Example
using System;
using System.Threading;
public class Multithreading
{
public void Display()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
Thread.Sleep(100);
}
}
}
public class MultithreadingDemo
{
public static void Main()
{
Multithreading multithreading = new Multithreading();
Thread thread1 = new Thread(new ThreadStart(multithreading.Display));
Thread thread2 = new Thread(new ThreadStart(multithreading.Display));
Console.WriteLine("Threads start execution");
thread1.Start();
thread2.Start();
try
{
//terminating execution of thread using Abort()
thread1.Abort();
thread2.Abort();
Console.WriteLine("Threads execution terminated");
}
catch (ThreadAbortException threadAbortException)
{
Console.WriteLine(threadAbortException.ToString());
}
}
}
Output:
- Join(): Used to make all calling threads wait until the current thread completes its execution and terminates.
Example:
using System;
using System.Threading;
public class Multithreading
{
public void Display()
{
for (int i = 0; i < 5; i++)
{
Thread thread = Thread.CurrentThread;
Console.WriteLine(thread.Name +" : "+i);
Thread.Sleep(100);
}
}
}
public class MultithreadingDemo
{
public static void Main()
{
Multithreading multithreading = new Multithreading();
Thread thread1 = new Thread(new ThreadStart(multithreading.Display));
Thread thread2 = new Thread(new ThreadStart(multithreading.Display));
Thread thread3 = new Thread(new ThreadStart(multithreading.Display));
//Assigning names to threads using Name property
thread1.Name = "Thread1";
thread2.Name = "Thread2";
thread3.Name = "Thread3";
thread1.Start();
//Making Thread2 and Thread3 wait until Thread1 completes execution
thread1.Join();
thread2.Start();
thread3.Start();
}
}
Output:
Advantages of Multithreading in C#
Below are some of the advantages in C#.
- Helps in maintaining a responsive user interface: Sometimes we have a time-consuming method in our application. In that case, if we make our application multithreaded, then other thread takes responsibility for the execution of that method while Main thread can focus on the responsiveness of the application. Thus, it will not freeze our application by timely giving a proper response to the user.
- Increases performance of the application: If we have as many threads as there are processor cores then each thread will run independently increasing the number of calculations per second.
- Threads minimize the use of system resources as they share the same address space.
- It makes code both faster and simpler at the same time.
Conclusion
Thread class provides many important properties like Priority, Name, IsAlive, background which we can use in our multithreading application. Thread Synchronization is a technique by which a thread can access a resource for a particular time without the interruption of other threads until it completes its task.
Recommended Articles
This has been a guide to the Multithreading in C#. Here we also discuss their basic concept, syntax, creation, and examples of multithreading in c#. You may also have a look at the following articles to learn more–