C# is a multi-paradigm programming language that supports several programming styles, including procedural, object-oriented, and functional programming. One of the essential features of C# is its support for multithreading, which enables developers to write applications that can perform multiple tasks concurrently.
To create a new thread in C#, you can use the Thread class. Here’s an example of how to create a new thread and start it:
C#
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread t = new Thread(Worker);
t.Start();
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Main thread doing some work");
Thread.Sleep(100);
}
t.Join();
Console.WriteLine("Done");
}
static void Worker()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Worker thread doing some work");
Thread.Sleep(100);
}
}
}
|
Output
Main thread doing some work
Worker thread doing some work
Main thread doing some work
Worker thread doing some work
Worker thread doing some work
Main thread doing some work
Main thread doing some work
Worker thread doing some work
Main thread doing some work
Worker thread doing some work
Main thread doing some work
Worker thread doing some work
Main thread doing some work
Worker thread doing some work
Main thread doing some work
Worker thread doing some work
Worker thread doing some work
Main thread doing some work
Worker thread doing some work
Main thread doing some work
Done
In this example, the Worker method is executed in a separate thread while the main thread is doing some other work. The Thread.Sleep method is used to simulate some work being done in both threads.
Another useful feature of C# is the ThreadPool class, which manages a pool of threads and can be used to execute tasks asynchronously. Here’s an example of how to use the ThreadPool class:
C#
using System;
using System.Threading;
class Program
{
static void Main()
{
ThreadPool.QueueUserWorkItem(Worker, "Hello, world!");
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Main thread doing some work");
Thread.Sleep(100);
}
Console.WriteLine("Done");
}
static void Worker(object state)
{
string message = (string)state;
for (int i = 0; i < 10; i++)
{
Console.WriteLine(message);
Thread.Sleep(100);
}
}
}
|
Output
Main thread doing some work
Hello, world!
Main thread doing some work
Hello, world!
Main thread doing some work
Hello, world!
Main thread doing some work
Hello, world!
Hello, world!
Main thread doing some work
Hello, world!
Main thread doing some work
Hello, world!
Main thread doing some work
Hello, world!
Main thread doing some work
Hello, world!
Main thread doing some work
Hello, world!
Main thread doing some work
Done
In this example, the Worker method is executed in a thread from the thread pool while the main thread is doing some other work. The ThreadPool.QueueUserWorkItem method is used to queue the work item to the thread pool. The state object can be used to pass data to the worker method.
These are just a couple of examples of how to use multithreading in C#. There are many other techniques and tools available to help you write efficient and scalable multithreaded applications.
Multitasking is the simultaneous execution of multiple tasks or processes over a certain time interval. Windows operating system is an example of multitasking because it is capable of running more than one process at a time like running Google Chrome, Notepad, VLC player, etc. at the same time. The operating system uses a term known as a process to execute all these applications at the same time. A process is a part of an operating system that is responsible for executing an application. Every program that executes on your system is a process and to run the code inside the application a process uses a term known as a thread. A thread is a lightweight process, or in other words, a thread is a unit which executes the code under the program. So every program has logic and a thread is responsible for executing this logic. Every program by default carries one thread to executes the logic of the program and the thread is known as the Main Thread, so every program or application is by default single-threaded model. This single-threaded model has a drawback. The single thread runs all the process present in the program in synchronizing manner, means one after another. So, the second process waits until the first process completes its execution, it consumes more time in processing. For example, we have a class named as Geek and this class contains two different methods, i.e method1, method2. Now the main thread is responsible for executing all these methods, so the main thread executes all these methods one by one.
Example:
CSharp
using System;
using System.Threading;
public class Geek {
public static void method1()
{
for (int I = 0; I <= 10; I++) {
Console.WriteLine("Method1 is : {0}", I);
if (I == 5) {
Thread.Sleep(6000);
}
}
}
public static void method2()
{
for (int J = 0; J <= 10; J++) {
Console.WriteLine("Method2 is : {0}", J);
}
}
}
public class GFG {
static public void Main()
{
Geek.method1();
Geek.method2();
}
}
|
Output:
Method1 is : 0
Method1 is : 1
Method1 is : 2
Method1 is : 3
Method1 is : 4
Method1 is : 5
Method1 is : 6
Method1 is : 7
Method1 is : 8
Method1 is : 9
Method1 is : 10
Method2 is : 0
Method2 is : 1
Method2 is : 2
Method2 is : 3
Method2 is : 4
Method2 is : 5
Method2 is : 6
Method2 is : 7
Method2 is : 8
Method2 is : 9
Method2 is : 10
Explanation: Here, first of all, method1 executes. In method1 , for loop starts from 0 when the value of i is equal to 5 then the method goes into sleep for 6 seconds and after 6 seconds it resumes its process and print remaining value. Until method2 is in the waiting state. method2 start its working when method1 complete its assigned task. So to overcome the drawback of single threaded model multithreading is introduced. Multi-threading is a process that contains multiple threads within a single process. Here each thread performs different activities. For example, we have a class and this call contains two different methods, now using multithreading each method is executed by a separate thread. So the major advantage of multithreading is it works simultaneously, which means multiple tasks execute at the same time. And also maximizing the utilization of the CPU because multithreading works on time-sharing concept mean each thread takes its own time for execution and does not affect the execution of another thread, this time interval is given by the operating system.
Example:
CSharp
using System;
using System.Threading;
public class GFG {
public static void method1()
{
for (int I = 0; I <= 10; I++) {
Console.WriteLine("Method1 is : {0}", I);
if (I == 5) {
Thread.Sleep(6000);
}
}
}
public static void method2()
{
for (int J = 0; J <= 10; J++) {
Console.WriteLine("Method2 is : {0}", J);
}
}
static public void Main()
{
Thread thr1 = new Thread(method1);
Thread thr2 = new Thread(method2);
thr1.Start();
thr2.Start();
}
}
|
Output :
Method1 is : 0
Method1 is : 1
Method1 is : 2
Method1 is : 3
Method2 is : 0
Method2 is : 1
Method2 is : 2
Method2 is : 3
Method2 is : 4
Method2 is : 5
Method2 is : 6
Method2 is : 7
Method2 is : 8
Method2 is : 9
Method2 is : 10
Method1 is : 4
Method1 is : 5
Method1 is : 6
Method1 is : 7
Method1 is : 8
Method1 is : 9
Method1 is : 10
Explanation: Here, we create and initialize two threads, i.e thr1 and thr2 using Thread class. Now using thr1.Start(); and thr2.Start(); we start the execution of both the threads. Now both thread runs simultaneously and the processing of thr2 does not depend upon the processing of thr1 like in the single threaded model. Note: Output may vary due to context switching. Advantages of Multithreading:
- It executes multiple process simultaneously.
- Maximize the utilization of CPU resources.
- Time sharing between multiple process.
Similar Reads
jQWidgets jqxKanban rtl Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The rtl property is used for setting or get
2 min read
Angular 10 I18nPluralPipe API
In this article, we are going to see what is I18nPluralPipe in Angular 10 and how to use it. The I18nPluralPipe is a map that takes a string value that pluralizes according to given rules. Syntax: {{ value | i18nPlural : map [ : rule]}} NgModule: Module used by I18nPluralPipe is: CommonModule Approa
2 min read
Angular 10 I18nSelectPipe API
In this article, we are going to see what is I18nSelectPipe in Angular 10 and how to use it. I18nSelectPipe is a selector that is used to displays the string that matches the current value. Syntax: {{ value | i18nSelect : map}} NgModule: Module used by I18nSelectPipe is: CommonModule Approach: Creat
2 min read
jQWidgets jqxKanban templateContent Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The templateContent property is used for se
2 min read
Angular10 percentPipe
In this article, we are going to see what is percentPipe in Angular 10 and how to use it. The percentPipe is used to Transform a number to a percentage string. Syntax: {{ value | percent [ : digitsInfo [ : locale ] ] }} NgModule: Module used by percentPipe is: CommonModule Approach: Create the angul
2 min read
jQWidgets jqxKanban resources Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The resources property is used for setting
2 min read
Create a User Blocking project using HTML CSS & JavaScript
The User Blocking project is a simple application that allows users to block or unblock certain users. It provides a basic interface to add users to a block list and remove them from the list. In this article, we are going to implement the functionality that can block a user by clicking a button and
4 min read
jQWidgets jqxKanban template Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The template property is used for setting o
2 min read
jQWidgets jqxKanban theme Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The theme property is used for setting or g
2 min read
Angular PrimeNG BlockUI Verification
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the BlockUI component Verification in Angular PrimeNG. The B
3 min read
jQWidgets jqxDropDownList rtl Property
Introduction: jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxDropDownList widget is a jQuery drop-down list that contains a list of selectable items displa
2 min read
jQWidgets jqxListMenu rtl Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxListMenu is a jQuery widget that is used to display a collection of Ordered and Unordered Lists. We can crea
2 min read
jQWidgets jqxKanban ready Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxKanban is used for representing the kanban method for a project. The ready property is used for setting or g
2 min read
Angular PrimeNG Styling of AvatarGroup
Angular PrimeNG is an open-source front-end UI library that has many native Angular UI components which help developers to build a fast and scalable web solution. In this article, we will be seeing Angular PrimeNG Styling of AvatarGroup. The AvatarGroup Component is used to group avatars together. T
3 min read
Angular PrimeNG Form Calendar Multiple Months Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the Calendar Form with the Multiple Months component in Angu
3 min read
Angular PrimeNG AvatarGroup
Angular PrimeNG is a UI component library for Angular Applications. It offers many pre-built themes and UI components for a variety of tasks like inputs, menus, charts, Buttons, etc. In this article, we will be seeing Angular PrimeNG AvatarGroup. The AvatarGroup Component is used to group avatars to
2 min read
Angular PrimeNG Timeline Opposite
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use the Timeline Opposite in Angular PrimeNG. We will also learn ab
3 min read
Angular PrimeNG Form Chips Templates
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use Angular PrimeNG Form Chips Templates Component. The Chips compo
3 min read
Angular PrimeNG BlockUI Document
Angular PrimeNG is a front-end UI toolkit for Angular applications. It has a wide variety of angular components that helps developers to build web applications in less time as they don't have to make everything from scratch. In this article, we will discuss BlockUI Document in Angular PrimeNG. The B
3 min read