You are on page 1of 14

C# Threading

KARTHIKEYAN R
18Y023
What are to be discussed:

► What is threading
► Synchronous and asynchronous
► Using of threads
► Methods of threads
► Thread Join
► Thread Sleep
► Thread Abort
Threading

► To define Threading in a one line, means parallel work or


code execution. To perform any multiple task
simultaneously means Threading.
► For example, executing Microsoft PPTX and Excel
simultaneously in a desktop, laptop or any device is known
as Threading.
► Work or a code task is always been executed in a two ways
i.e. Synchronous or Asynchronous way.
Synchronous way means within a given work multiple
jobs are executed one after the other.
Here, Work 2 has to wait till Work 1 is completed; same
way the others as shown in image given below.
Asynchronous means multiple jobs
can be executed simultaneously just
like doing multiple tasks at the
same time.

(Execution of Microsoft Power point and


Excel asynchronously on our personal
laptop is the most common example for
threading)
Using of threads

Step 1:
First and foremost step is to import the Threading namespace.

using System;
using System.Threading
Step 2:
Here in this step we will create thread objects
in our Main method.
class Program
{
static void Main(string[] args)
{
Thread oThreadone =new
Thread(Work1);
Thread oThreadtwo = new
Thread(Work2);

}
}
Step 3:
In this step we will invoke our thread objects
class Program
{
static void Main(string[] args)
{
Thread oThreadone = new Thread(Work1);
Thread oThreadtwo = new Thread(Work2);

oThreadone.Start();
oThreadtwo.Start();
}
}
• As you see, we have invoked Thread
objects successfully.
• Now, let's run this program to see the
Output.....
• As you can see, in the output,
method Work2 is simultaneously
executing along with the method
Work1.
• It means that both of these
methods are working
asynchronously.
THREAD.Sleep

► Thread.Sleep is a method used to suspend current thread for a specific


interval of time.
► Time can be specified in milliseconds or Timespan.
► While in the Sleep mode, a method does not consumes any CPU resources
so indirectly it saves memory for the other thread processes to execute.
THREAD.Join
► Thread.Join() method makes a thread to finish its work or makes the
other thread to halt until it finishes work.
► Join method, when attached to any thread, makes that thread to execute
first and halts the other threads.
► This enables both the threads synchronize.
THREAD.Abort
► As the name implies, Thread.Abort() method is used for aborting the thread
on which it is invoked.
► It raises an exception named ThreadAbortException on that thread before
the process of termination begins.
► It is an overloaded method with the following two forms:
Abort() - On the current thread
Abort(Object) - On the thread which is passed as argument
► Calling this method usually terminates the thread.
THANK YOU!!

You might also like