Introduction to Multithreading in C#
Multithreading in C# enables simultaneous execution of multiple threads within a single process, allowing developers to create responsive and efficient applications. Threads are independent execution paths, allowing tasks to run concurrently, utilizing available CPU resources effectively. This concurrent execution is beneficial for tasks such as parallel processing, handling user interfaces, and optimizing application performance. In C#, multithreading can be achieved using the System.Threading namespace provides classes and methods to create, manage, and synchronize threads. However, developers must be cautious when dealing with shared resources to prevent race conditions and ensure thread safety through proper synchronization techniques like locks, monitors, and mutexes.
Table of Content
- Introduction
- What is Multithreading in C#?
- Syntax with Explanation
- Understanding Multithreading in C#
- How does Multithreading in C# make working so easy?
- Example using Thread Class
- Example using ThreadStart delegate
- Example using Sleep()
- Example using Abort()
- Example using Join()
- Advantages
What is Multithreading in C#?
Multithreading in C# is a way of executing multiple tasks or processes simultaneously. To achieve multithreading, it requires a multitasking operating system.
Execution of every program is a process and a process uses a term called thread to run the code inside an application. The thread is a lightweight process that specifies the execution path of a program.
Multithreading in C# defines executing multiple tasks at a time and uses System. Threading namespace to create a multithreaded application in C#.
Windows operating system is an example of multitasking; it can run more than one process at a time such as running Google Chrome, text editor, Windows media player, etc at the same time.
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();
Understanding Multithreading in C#
You can understand the process of multithreading with the help of System.Threading.Thread class. It starts when an object of this class is created and ends when the thread has completed the execution.
Multithreading contains the following life cycle:
- Unstarted State: This state defines an instance of the thread is created, but yet to call the start method.
- Ready State: In this state, the thread is ready to run and waiting for CPU cycle.
- Not Runnable State: This state occurs when sleep and wait method has been called and blocked by I/O operations.
- Dead State: It represents thread has completed the execution or is aborted.
How does Multithreading in C# make working so easy?
Multithreading in C# makes working easy with an application because of the following points:
- Multithreading provides parallelism in a multiprocessor environment, in which different types of processors can be executed parallel by threads.
- By working parallel with Multithreading, there will be an increase in the responsiveness of a user interface.
- If one thread is waiting for a response from another computer, then other threads can continue execution.
- Threads can distinguish tasks based on priority; critical tasks managed by the high-priority thread, and low-priority thread manages other tasks.
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:
What can you do with Multithreading in C#?
By using Multithreading, you can execute multiple tasks simultaneously over a certain time interval. As we have discussed, every program run inside an application by using a thread. Therefore, the thread is responsible for executing the logic of every program which is often known as Main Thread of an application. In the present situation, every application uses multiple threading. An application contains user interface thread which can interact with the user and background worker threads that perform other tasks.
Advantages
Following is the list of few advantages :
- Multithreading in C# improves the performance of the processor by executing computation and I/O operations simultaneously.
- It minimizes the usage of system resources by using threads, which share the same address space that belong to the same process.
- Multithreading maintains the responsive user interface.
- You can access multiple applications at the same time, because of quick context switching among threads.
- Multithreading simplifies complex program structure by writing each activity in separate methods.
Required skills
Multithreading is based on the C and C++ programming languages. If you have a basic understanding of C or C++ programming, then you can easily learn C#. It follows the features of high-level languages like C or C++ and being an object-oriented language, it has strong similarity representation with Java.
Along with the above skills, the candidate should have below skills which could help in developing applications:
- Client-side web development technologies
- Databases
- Microsoft Certified Solutions Developer (MCSD)
- Microsoft Most Valuable Professional (MVP)
- WEB API
- AZURE
- SharePoint
- Other JavaScript libraries and frameworks
Why should we use Multithreading in C#?
We should use or we need Multithreading in C# to perform the multiple tasks at a time. The main objective of multithreading is to execute two or more parts of a program at a time to utilize the CPU time. The multithreaded program includes two or more parts that can run concurrently.
We need Multithreading in C# for the following reasons:
- It maintains a responsive user interface.
- Performs parallel programming to execute calculations faster on multiprocessor systems.
- It handles the requests simultaneously on both server and client side. For instance, handling peer-to-peer networking.
Who is the right audience for learning Multithreading in C# technologies?
Multithreading in C# technologies has a large target audience as it is developed by Microsoft Corporation. It has a larger community because it develops new tools and software’s to make it exist in the system. Beginners can easily learn the C# technology if they have basic knowledge of C programming language. It is widely used by software developers who develop Windows desktop applications and games.
How this technology will help you in career growth?
C# is a powerful server-side application framework for developing static or dynamic web applications. Developers recognize its strength for web development, positioning .NET technology for a promising future. The demand for applications built on this technology is currently high. So to make career better in the web development field, everyone wants to learn this technology as its high in demand nowadays. To become a developer, you need to learn Microsoft .NET framework. Once you finish learning, you can apply for developer jobs and can look for a good package annually.
Conclusion
Multithreading in C# allows simultaneous execution of multiple tasks, enhancing performance and responsiveness in applications. By leveraging the System.Threading namespace, developers can create threads and manage their lifecycle. C# facilitates parallelism, improves CPU utilization, and maintains a responsive user interface. It’s essential for web development, games, and desktop applications. With its demand in the industry, learning C# multithreading boosts career prospects, particularly for developers aiming for roles in web development and software engineering within the Microsoft ecosystem.
Recommended Articles
We hope that this EDUCBA information on “What is Multithreading in C#?” was beneficial to you. You can view EDUCBA’s recommended articles for more information.