- Today,we will discuss MultiThreading in C#.Before we discuss multithreading, first let's understand the multitasking.
There are two distinct types of multitasking:
process-based and thread-based. It is important to understand the difference between the two.
- Process is what the operating system uses to facilitate the execution of a program by providing the resources required. Each process has a unique process Id associated with it. You can view the process within which a program is being executed using windows task manager.Thus, process-based multitasking is the feature that allows your computer to run two or more programs concurrently. For example, process-based multitasking allows you to run a word processor at the same time you are using a spreadsheet or browsing the Internet. In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.
- Thread is a light weight process. A process has at least one thread which is commonly called as main thread which actually executes the application code. A single process can have multiple threads.In a thread-based multitasking environment, all processes have at least one thread, but they can have more. This means that a single program can perform two or more tasks at once. For instance, a text editor can be formatting text at the same time that it is printing, as long as these two actions are being performed by two separate threads.
The differences between process-based and thread-based multitasking can be summarized like this: Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program.
One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application. So far we wrote the programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads.
- Single threaded Applications Single threaded applications are those in which a thread cannot execute until the earlier thread has completed its execution. The MS-DOS operating system is an example of a single threaded operating system. These environments do not have any support for Multithreading and they monopolize the processor and have low system throughput. Throughput is a measure of the amount of the job done in unit time.
- Multithreading Applications Multithreading is the ability of the operating system to have at the same point of time multiple threads in memory which switch between the tasks so as to provide a pseudo parallelism, as if all the tasks are running simultaneously. This illusion of concurrency is ensured by the Operating System by providing a specific time slice to each and every thread and then switching between the threads once their slice is over. This switching is very fast. The switching between the threads involves a context switch which in turn involves saving the current thread’s state, flushing the CPU and handling control of the CPU to the next thread in the queue. Remember that at any point of time the CPU can execute only one thread. It is to be noted here that Multiprocessing involves multiple processor with each executing one thread at any particular point of time.
Advantages and Disadvantages of Multithreading
- To maintain a responsive user interface
- Faster execution
- To make efficient use of processor time while waiting for I/O operations to complete.
- To split large, CPU-bound tasks to be processed simultaneously on a machine that has multiple CPUs/cores.
- Support for Concurrency
Disadvantages of multithreading:
- On a single-core/processor machine threading can affect performance negatively as there is overhead involved with context-switching.
- Have to write more lines of code to accomplish the same task.
- Multithreaded applications are difficult to write, understand, debug and maintain
- Unstarted State: When the instance of the thread is created but the Start method is not called.
- Ready State: When the thread is ready to run and waits for CPU cycle.
- Sleep method has been called.
- Wait method has been called.
- Blocked by I/O operations.
The Dead State: When the thread is in the condition, given below:
- Completes execution.
- Aborted.
Constructors
Thread(ThreadStart) Initializes a new instance of the Thread class.
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.
Properties
Name Gets or sets the name of the thread.
ThreadState Gets a value containing the states of the current thread.
Priority Gets or sets a value indicating the scheduling priority of a thread.
ManagedThreadId Gets a unique identifier for the current managed thread.
IsAlive Gets a value indicating the execution status of the current thread.
CurrentThread Gets the currently running thread.
Methods
Start() Causes the operating system to change the state of the current instance to ThreadState.Running.
Start(Object) Causes the operating system to change the state of the current instance to ThreadState.Running, and optionally supplies an object containing data to be used by the method the thread executes.
Sleep(Int32) Suspends the current thread for the specified number of milliseconds.
Join() Blocks the calling thread until the thread represented by this instance terminates, while continuing to perform standard COM andcSendMessage pumping.
Finalize() Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object. (Overrides CriticalFinalizerObject.Finalize().)
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.
ToString() Returns a string that represents the current object.(Inherited fromObject.)
Now, i will explain how to start, abort,suspend and resume the thread by example.
Starting a Thread
A C# client program starts in a single thread created automatically by the CLR and operating system that is called the main thread, and is made multithreaded by creating additional threads. Here's a simple example and its output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace multi
{
class Program
{
static void Main(string[] args)
{
Thread th = new Thread(WriteY);
th.Start();
for (int i = 0; i <= 10; i++)
{
Console.WriteLine("Hello");
}
}
private static void WriteY()
{
for (int i = 0; i <= 9; i++)
{
Console.Write("world");
}
}
}
}
OUTPUT
In the above example, the main thread creates a new thread on which it runs a method that repeatedly prints the string "world". Simultaneously, the main thread repeatedly prints the string "Hello".
Abort a Thread
The Thread class's Abort method is called to abort a thread. Make sure you check the IsAliveproperty before Abort.
if (Thread.IsAlive)
{
{
Thread.Abort();
}
Here's a simple example and its output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace multi
{
class Program
{
static void Main(string[] args)
{
Thread th = new Thread(WriteY);
if (th.IsAlive)
{
th.Start();
th.Abort();
}
for (int i = 0; i <= 10; i++)
{
Console.WriteLine("Hello");
}
}
private static void WriteY()
{
for (int i = 0; i <= 9; i++)
{
Console.WriteLine("world");
}
}
}
}
OUTPUT

Suspend a Thread
The Suspend method of the Thread class suspends a thread. The thread is suspended until the Resume method is called.
if (thread.ThreadState == ThreadState.Running)
{
{
thread.Suspend();
}
Resume a suspended Thread
The Resume method is called to resume a suspended thread. If the thread is not suspended, the Resume method will have no effect.
if (thread.ThreadState == ThreadState.Suspended) {
thread.Resume();
}
You may also like
1)Abstraction and Encapsulation in OOPS
2)Inheritance in OOPS
3)Polymorphism in OOPS
4)Interface in OOPS
5)What is Virtual Function
6)What is Abstract class and Abstract function
7)What is Static Class and Static Members
8)What is Collections
9) What is Generics
10)What is Delegate
11)Exception Handling
12)Static Constructor
You may also like
1)Abstraction and Encapsulation in OOPS
2)Inheritance in OOPS
3)Polymorphism in OOPS
4)Interface in OOPS
5)What is Virtual Function
6)What is Abstract class and Abstract function
7)What is Static Class and Static Members
8)What is Collections
9) What is Generics
10)What is Delegate
11)Exception Handling
12)Static Constructor
1)How to make a Registration Page using CAPTCHA in C#
2)How to make a Login Window in C# - Step by Step
3)How to make PhoneBook in C#
4)Insert,Update ,Delete in a C#
2)How to make a Login Window in C# - Step by Step
3)How to make PhoneBook in C#
4)Insert,Update ,Delete in a C#
great
ReplyDeleteHi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
ReplyDeleteor Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.
Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
ReplyDeleteData Science course in kalyan nagar
Data Science course in OMR
Data Science course in chennai
Data science course in velachery
Data science course in jaya nagar
Data Science interview questions and answers
Data science course in bangalore
Get a lot of fun playing with us in the online casino. roulettes free with us We all love to play in the Internet online casino, let's play with us and earn.
ReplyDeleteNice blog,I understood the topic very clearly,And want to study more like this.
ReplyDeleteData Scientist Course
Cool stuff you have and you keep overhaul every one of us
ReplyDeletedata science course
Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
ReplyDeleteSimple Linear Regression
Correlation vs Covariance
It is perfect time to make some plans for the future and it is time to be happy. I've read this post and if I could I desire to suggest you some interesting things or suggestions. Perhaps you could write next articles referring to this article. I want to read more things about it!
ReplyDeleteData Science Course
I’m happy I located this blog! From time to time, students want to cognitive the keys of productive literary essays composing. Your first-class knowledge about this good post can become a proper basis for such people. nice one
ReplyDeleteData Science Training
Well explained article and impressive too..
ReplyDeleteJava training in Chennai | Certification | Online Course Training | Java training in Bangalore | Certification | Online Course Training | Java training in Hyderabad | Certification | Online Course Training | Java training in Coimbatore | Certification | Online Course Training | Java training in Online | Certification | Online Course Training
I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.
ReplyDeletedata science interview questions
Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
ReplyDeleteCorrelation vs Covariance
Simple linear regression
data science interview questions
Attend The Data Science Courses From ExcelR. Practical Data Science Courses Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Science Courses. data science courses
ReplyDeleteVery interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.
ReplyDelete360DigiTMG Data Science Course In Pune
360DigiTMG Data Science Training In Pune
Thank you..
I am looking for and I love to post a comment that "The content of your post is awesome" Great work!
ReplyDeleteSimple Linear Regression
Correlation vs Covariance
Very nice blogs!!! i have to learning for lot of information for this sites…Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing, data sciecne course in hyderabad
ReplyDeleteReally nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
ReplyDeleteSimple Linear Regression
Correlation vs covariance
KNN Algorithm
Logistic Regression explained
Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing.data science course Hyderabad
ReplyDeleteNice content very helpful, It has a very important point which should be noted down. All points mentioned and very well written.Keep Posting & writing such content
ReplyDeleteAWS Online Training
Online AWS Certification Training
so happy to find good place to many here in the post, the writing is just great, thanks for the post.
ReplyDeleteBest Institute for Data Science in Hyderabad
Wow, What a Excellent post. I rceally found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thankdata science courses
ReplyDeleteSo, we can say that Artificial Intelligence (AI) is the branch of computer sciences that emphasizes the development of intelligence machines, thinking and working like humans. For example, speech recognition, problem-solving, learning and planning. data science course in india
ReplyDelete