0% found this document useful (0 votes)
12 views

Unit7 C#

C# supports multithreading which allows multiple parts of a program to run concurrently. Each concurrent part is called a thread, which is a separate sequence of instructions that performs a specific task like reading data or printing results. Multithreading allows multiple tasks to be performed simultaneously during program execution. The main advantage is that it allows programs to make more efficient use of computer resources like memory, I/O devices, and time. C# includes the System.Threading namespace required for developing multithreaded programs. A thread goes through states like unstarted, runnable, running, not runnable, and dead during its lifecycle.

Uploaded by

Aarti Shinde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Unit7 C#

C# supports multithreading which allows multiple parts of a program to run concurrently. Each concurrent part is called a thread, which is a separate sequence of instructions that performs a specific task like reading data or printing results. Multithreading allows multiple tasks to be performed simultaneously during program execution. The main advantage is that it allows programs to make more efficient use of computer resources like memory, I/O devices, and time. C# includes the System.Threading namespace required for developing multithreaded programs. A thread goes through states like unstarted, runnable, running, not runnable, and dead during its lifecycle.

Uploaded by

Aarti Shinde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Threading|2020

C# support the concept of multithreading which enable us to execute two or more


parts of program concurrently. Each part is known as thread. A thread is basically a
separate sequence of instruction designed for performing a specific task in the
program. A task may represent an operation such as reading data, printing some
result or performing certain calculation. Multithreading therefore means performing
multiple task at the same time during the execution of program. The execution of C#
program start with single thread called main thread i.e. automatically run by CLR and
OS. The process of developing a program for execution with multiple thread is called
multithreaded programming and the process of execution is called multithreading.
The main advantage of multithreading is that it enable us to develop efficient
program that could optimize the use of computer resource such as memory, I/O
device and time.
C# define a namespace known as System. Threading that are required for
developing and running multithreading program. Therefore we must include
statement is.
Using system. Threading;
Multithreading Fundamentals
There are two distinct type of multitasking
1) Process based 2) Thread Based
1) Process based
A process is a program that is executing, thus process based multitasking is the
feature that allows your computer to run two or more program concurrently.
Ex.Process based multitasking allow 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 scheduler.
2) Thread Based
A thread is dispatch cable unit of executable code. The name comes from the
concept thread based multitasking environment all processes have at least one
thread, but they can have more also. This means that a single program can perform
two or more task at once.
E.g. For instance a text editor can be formatting text at the same time it is printing as
long as these actions are being performed by two separate methods.
The difference between process based and thread based multitasking can be
summarized like this process based multitasking handle the concurrent execution of
program. Thread based multitasking deals with concurrent execution of piece of same
program.

PAWAR A.R. (SANGOLA COLLEGE SANGOLA) 1


Threading|2020
Thread Life cycle

1. Unstarted state: When an instance of a Thread class is created, it is in the


unstarted state, means the thread has not yet started to run when the thread is in
this state. Or in other words Start() method is not called.
Thread thr = new Thread();
Here, thr is at unstarted state.
2. Runnable State: A thread that is ready to run is moved to runnable state. In this
state, a thread might actually be running or it might be ready to run at any
instant of time. It is the responsibility of the thread scheduler to give the thread,
time to run. Or in other words, the Start() method is called.
3. Running State: A thread that is running. Or in other words, the thread gets the
processor.
4. Not Runnable State: A thread that is not executable because
 Sleep() method is called.
 Wait() method is called.
 Due to I/O request.
 Suspend() method is called.
5. Dead State: When the thread completes its task, then thread enters into dead,
terminates/stope, abort state.

PAWAR A.R. (SANGOLA COLLEGE SANGOLA) 2


Threading|2020
Thread class provides different types of methods to implement the states of the
threads.
 Sleep()- method is used to temporarily suspend the current execution of the
thread for specified milliseconds, so that other threads can get the chance to start
the execution, or may get the CPU for execution.
 Join() - method is used to make all the calling thread to wait until the main
thread, i.e. joined thread complete its work.
 Abort() -method is used to abort the thread.
 Suspend() -method is called to suspend the thread.
 Resume()- method is called to resume the suspended thread.
 Start() -method is used to send a thread into runnable State.

Thread Class

The thread class helps us to perform task such as creating and setting the
priority of thread. We can use this class to control a thread and obtain it’s status.
The thread class provide various properties that allow us to perform task such
as obtaining a status of thread and specifying a name for thread. Following table
shows the important method of thread class.
Method Task
Start To start thread
Sleep To block the current thread for a specified time period
Suspend To suspend a thread
Resume To resume a thread which has been suspend
Join To block a thread until another thread has terminated
Interrupt To interrupt the thread which is in the sleep,join,wait state
SpinWait To make a thread wait the no of time specified in iteration
parameter.

Creating and manipulating threads


A thread can be created in C#.using the constructor of the thread class. We need to
pass the ThreadStart delegate to the thread class constructor along with method for
which execution should start. To create a thread in c# .we can use the following
statement.
Thread threadname= new Thread(new ThreadStart(methodname));

using System;
using System.Collections.Generic;

PAWAR A.R. (SANGOLA COLLEGE SANGOLA) 3


Threading|2020
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication2
{
class demo
{
public void first()
{
Console.WriteLine("First method is run for Thread t1");
Thread.Sleep(500);
Console.WriteLine("First method is terminated");
}
public void second()
{
Console.WriteLine("second method is run for Thread t2");
Thread.Sleep(500);
Console.WriteLine("second method is terminated");
}
}
class Program
{
static void Main(string[] args)
{
demo d = new demo();
Thread t1 = new Thread(d.first);
Thread t2 = new Thread(d.second);
Console.WriteLine("Thread t1 is started");
t1.Start();
Console.WriteLine("Thread t2 is started");
t2.Start();
Console.ReadKey();
}
}
}

Multiple Thread (Multiple Threads with single application i.e.


Method)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

PAWAR A.R. (SANGOLA COLLEGE SANGOLA) 4


Threading|2020
using System.Threading;
namespace ConsoleApplication1
{
class mythread
{
int c;
Thread thr;
public mythread(string n)
{
c = 0;
thr = new Thread(show);
thr.Name = n;
thr.Start();
}
public void show()
{
Console.WriteLine(Thread.CurrentThread.Name + " starting");
do
{
Console.WriteLine("In " + thr.Name + " Count is " + c);
Thread.Sleep(500);
c++;
} while (c < 4);
Console.WriteLine(thr.Name + " Terminated");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main thread is started");
mythread t1 = new mythread("Thread t1");
mythread t2 = new mythread("Thread t2");
mythread t3 = new mythread("Thread t3");
Console.ReadKey();
}
}
}

Thread Priorities

Each thread has a priority setting associated with it .A thread priority determine
impart how frequently a thread gain access to the CPU.In general low priority thread
gain access to the CPU less often than high priority thread. As a result within given

PAWAR A.R. (SANGOLA COLLEGE SANGOLA) 5


Threading|2020
period of time low priority thread will often receive less CPU time than a high priority
thread.
It is important to understand that factors other than thread priority can also
affect how frequently a thread gain access to the CPU.
EX. If a high priority thread is waiting on some resource (perhaps for keyboard I/P)
It will be blocked and lower priority thread will run. Thus in this situation a low
priority thread may gain greater access to CPU than the high priority thread over a
specific period. Finally how task scheduling is implemented by OS.Afftect how CPU
time is allocated.
When a child thread is started, it receive default priority setting. You can
change thread priority through the priority, which is member of thread.
Threadpriority is an enumeration that define following 5 priority setting.

ThreadPriority.Highest;
ThreadPriority.AboveNormal;
ThreadPriority.Normal;
ThreadPriority.BelowNormal;
ThreadPriority.BelowNormal;
ThreadPriority.Lowest;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication3
{
class demo
{
public void read1()
{
Console.WriteLine("Thread t1 is started");
Console.WriteLine("Priority of t1 is " +
Thread.CurrentThread.Priority);
}
public void read2()
{
Console.WriteLine("Thread t2 is started");
Console.WriteLine("Priority of t2 is " +
Thread.CurrentThread.Priority);

}
public void read3()

PAWAR A.R. (SANGOLA COLLEGE SANGOLA) 6


Threading|2020
{
Console.WriteLine("Thread t3 is started");
Console.WriteLine("Priority of t3 is " +
Thread.CurrentThread.Priority);
}
public void read4()
{
Console.WriteLine("Thread t4 is started");
Console.WriteLine("Priority of t4 is " +
Thread.CurrentThread.Priority);
}
public void read5()
{
Console.WriteLine("Thread t5 is started");
Console.WriteLine("Priority of t5 is " +
Thread.CurrentThread.Priority);
}
}

class Program
{
static void Main(string[] args)
{
demo d = new demo();
Thread t1 = new Thread(d.read1);
Thread t2 = new Thread(d.read2);
Thread t3 = new Thread(d.read3);
Thread t4 = new Thread(d.read4);
Thread t5 = new Thread(d.read5);

t1.Priority = ThreadPriority.Lowest;
t2.Priority = ThreadPriority.BelowNormal;
t4.Priority = ThreadPriority.AboveNormal;
t5.Priority = ThreadPriority.Highest;

t1.Start();
t2.Start();
t3.Start();
t4.Start();
t5.Start();
Console.ReadKey();
}
}
}

Synchronization

PAWAR A.R. (SANGOLA COLLEGE SANGOLA) 7


Threading|2020
When using multiple threads you will sometime need to co-ordinate the activities of
two or more threads. The process by which this is achieved is called synchronization.
The most common reason for using synchronization when two or more threads need
to access a shared resource that can be used by only one thread at a time.
Another situation in which synchronization is needed when one thread is
waiting for an event that is caused by another thread. In this case there must be some
means by which the first thread is held in suspend state until the event has occurred
then the waiting thread must resume execution.
The key to synchronization is a concept of lock which control access to
block of code within an object .when an object is locked by one thread, no other
thread can gain access to the locked block of code. When the thread release lock, the
object is available for used by another thread.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication4
{
class demo
{
int x = 90, y = 10, sum;
private object lock_obj = new object();
public void lock_demo()
{
sum = 0;
Console.WriteLine(Thread.CurrentThread.Name + " is started");
lock(lock_obj )
{
sum = x + y;
}
Console.WriteLine("In thread " + Thread.CurrentThread.Name + "
Sum is" + sum);
Thread.Sleep(500);
Console.WriteLine(Thread.CurrentThread.Name + "Terminated");
}
}
class Program
{
static void Main(string[] args)
{
demo d = new demo();

PAWAR A.R. (SANGOLA COLLEGE SANGOLA) 8


Threading|2020
Thread t1 = new Thread(d.lock_demo);
Thread t2 = new Thread(d.lock_demo);
Thread t3 = new Thread(d.lock_demo);
t1.Name = "Thread t1";
t2.Name = "Thread t2";
t3.Name = "Thread t3";

t1.Start();
t2.Start();
t3.Start();
Console.ReadKey();
}
}
}

PAWAR A.R. (SANGOLA COLLEGE SANGOLA) 9

You might also like