0% found this document useful (0 votes)
591 views20 pages

Multithreading in C#

The document discusses threading in C# and .NET, including how to create and start threads, set thread priorities, synchronize thread access using locks and monitors to prevent race conditions and deadlocks, and common threading methods like Start(), Join(), Abort(), and Suspend(). It provides examples of creating and running multiple threads that display output, and using locks and monitors to synchronize access to shared resources between threads.

Uploaded by

Ritesh Joshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
591 views20 pages

Multithreading in C#

The document discusses threading in C# and .NET, including how to create and start threads, set thread priorities, synchronize thread access using locks and monitors to prevent race conditions and deadlocks, and common threading methods like Start(), Join(), Abort(), and Suspend(). It provides examples of creating and running multiple threads that display output, and using locks and monitors to synchronize access to shared resources between threads.

Uploaded by

Ritesh Joshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 20

Threading using C# and .

Net
using System; Threading
using System.Threading;
public class Test
{
public static void Main(string[] ar)
{
Thread t1= new Thread(new ThreadStart(Display1));
Thread t2= new Thread(new ThreadStart(Display2));
t1.start();
t2.start();
}
public static void Display1()
{
for(int i=0; i<20; i++)
{
Console.WriteLine(i);
}
}
public static void Display2()
{
for(int i=0; i<20; i++)
{
Console.WriteLine(“Welcome”);
}
}
}
Threads :
• Thread is the fundamental unit of execution.

• More than one thread can be executing code


inside the same process (application).

• On a single-processor machine, the


operating system is switching rapidly
between the threads, giving the
appearance of simultaneous execution.
• With threads you can :

▫ Maintain a responsive user interface while


background tasks are executing

▫ Distinguish tasks of varying priority

▫ Perform operations that consume a large amount


of time without stopping the rest of the application
• Starting a thread :

Thread thread = new Thread(new ThreadStart (ThreadFunc));


//Creates a thread object
// ThreadStart identifies the method that the thread executes when it starts

thread.Start();
//starts the thread running

Thread Priorities :
Controls the amount of CPU time that can be allotted to a thread.

ThreadPriority.Highest
ThreadPriority.AboveNormal
ThreadPriority.Normal
ThreadPriority.BelowNormal
ThreadPriority.Lowest
Inter-thread Communication
Thread lifecycle

• Waiting and ready queues


• States

Running Suspended

Unstarted Aborted

WaitSleepJoin
Inter-thread Communication
Thread lifecycle

Running
8

C# Threading

Thread Methods
• Start()
▫ Begins execution of the thread
▫ Once a thread is finished, it cannot be restarted

• Suspend() Thread.Suspend
▫ Suspends the thread
▫ If the thread is already suspended, there is no effect

• Resume() Thread.Resume
▫ Resumes a suspended thread

• Interrupt()
▫ Resumes a thread that is in a WaitSleepJoin state
▫ If the thread is not in WaitSleepJoin state it will be interrupted next time it is blocked
9

C# Threading

Thread Methods (Continued)


• Abort() Thread.Abort()
▫ Terminating a running thread.
▫ Throws a ThreadAbortException
▫ In order to end the thread , Abort() throws a
ThreadAbortException.

• Join()
▫ Blocks the calling thread until the owning thread terminates
• A thread can prevent itself from being terminated
with Thread.ResetAbort.
try{

}
catch(ThreadAbortException)
{
Thread.ResetAbort();
}

• Thread.Join()
▫ When one thread terminates another, wait for the
other thread to end.
• Thread Synchronization :
▫ Threads must be coordinated to prevent data
corruption.

• Monitors
▫ Monitors allow us to obtain a lock on a particular
object and use that lock to restrict access to critical
section of code.

▫ While a thread owns a lock for an object, no other


thread can acquire that lock.

▫ Monitor.Enter(object) claims the lock but blocks if


another thread already owns it.

▫ Monitor.Exit(object) releases the lock.


using System;
Thread Synchronization
using System.Threading;
public class Test
{
public static void Main(string[] ar)
{ Test k = new Test();
Thread t1= new Thread(new ThreadStart(k.Display1));
Thread t2= new Thread(new ThreadStart(k.Display2));
t1.start(); t2.start();
k.Display1();
}
public void Display1()
{ lock(this)
for(int i=0; i<10; i++)
{
Console.WriteLine(i);
} }
public void Display2()
{ lock(this)
for(int i=0; i<5; i++)
{
Console.WriteLine(“Welcome”);
} }

}
Thread Synchronization
using System.Threading;
namespace CSharpThreadExample
{
class Program
{ static void Main(string[] arg)
{ Console.WriteLine("*****Multiple Threads*****");
Printer p=new Printer();
Thread[] Threads=new Thread[3];
for(int i=0;i<3;i++)
{ Threads[i]=new Thread(new ThreadStart(p.PrintNumbers));
Threads[i].Name="Child "+i; }
foreach(Thread t in Threads)
t.Start();
Console.ReadLine();
} }
class Printer
{ public void PrintNumbers()
{ for (int i = 0; i < 5; i++)
{ Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
} }
}
Thread Synchronization
public void PrintNumbers()
{ Monitor.Enter(this);
try
{ for (int i = 0; i < 5; i++)
{ Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
finally
{ Monitor.Exit(this);
} }
Synchronization
Using a lock Block
SyncLock
• Example: lock block in C# In VB.NET

Object whose lock is obtained

lock (this)
{
workQueue[nextFreeElement] = unit;
nextFreeElement++; } Critical
code
}

Lock released at end of block


• The C # Lock Keyword :

lock(buffer)
{ ……. }

is equivalent to

Monitor.Enter(buffer);
try
{ critical section; }
finally
{ Monitor.Exit(buffer); }

- Also ensures the presence of a finally block to make sure the lock is released.
Synchronization
Obtaining Locks with Monitors

• Example: Monitor usage in C#

Monitor.Enter(this);

workQueue[nextFreeElement] = unit;
nextFreeElement++; } Critical
code
Monitor.Exit(this);

Must remember to explicitly release the lock


19

C# Threading

Threading Dangers
• Race Conditions
▫ When multiple threads access the same memory
▫ A thread is interrupted while updating memory
▫ Solution: “lock” memory in a mutex, monitor, etc.

• Deadlock
▫ Two or more threads waiting on each other to release resources
20

C# Threading

Deadlock
• Your job to avoid it

waiting for has


object1

Resource1 Resource1

object2 waiting for


has

You might also like