MULTITHREADING
Definition 
Threading: A thread is an independent execution path, able to run 
simultaneously with other threads. 
Multithreading: Multithreading is used to perform multiple tasks at the 
same time.
Thread life cycle
Creation 
• C# supports 2 methods to create threads 
 Using the Thread class. 
 Using the Thread pool. 
Thread Class: 
 A new thread object is created and a delegate is passed to the thread’s constructor. 
Thread Pool: 
 C# provides a pool of threads. Tasks can be assigned to the threads in the pool.
Thread Class: 
Thread thread1 = new Thread(new ThreadStart(Thread1)); 
Thread thread2 = new Thread(new ThreadStart(Thread2)); 
//thread2.Priority = ThreadPriority.Highest; 
thread1.Name = "First"; 
thread2.Name = "Second"; 
thread1.Start(); 
thread2.Start();
Synchronization: 
lock (this) 
{ 
for(int i=0;i<5;i++) 
Console.WriteLine(“Current thread is {0} and value of i is {1} ”,Thread.CurrentThread.Name,i); 
}
Thread Communication:
Wait() Method: 
Releases the lock on an object and blocks the current thread until it reacquires 
the lock. 
Syntax: Monitor.Wait(object); 
Pulse() Method: 
Notifies a thread in the waiting queue of a change in the locked object's state. 
Syntax: Monior.Pulse(object);
Deadlock: 
 A deadlock is a situation where an application locks up because two or more activities are 
waiting for each other to finish. 
lock(lock1) 
{ 
lock(lock2) 
{…} 
}

multi threading

  • 1.
  • 2.
    Definition Threading: Athread is an independent execution path, able to run simultaneously with other threads. Multithreading: Multithreading is used to perform multiple tasks at the same time.
  • 3.
  • 4.
    Creation • C#supports 2 methods to create threads  Using the Thread class.  Using the Thread pool. Thread Class:  A new thread object is created and a delegate is passed to the thread’s constructor. Thread Pool:  C# provides a pool of threads. Tasks can be assigned to the threads in the pool.
  • 5.
    Thread Class: Threadthread1 = new Thread(new ThreadStart(Thread1)); Thread thread2 = new Thread(new ThreadStart(Thread2)); //thread2.Priority = ThreadPriority.Highest; thread1.Name = "First"; thread2.Name = "Second"; thread1.Start(); thread2.Start();
  • 7.
    Synchronization: lock (this) { for(int i=0;i<5;i++) Console.WriteLine(“Current thread is {0} and value of i is {1} ”,Thread.CurrentThread.Name,i); }
  • 8.
  • 9.
    Wait() Method: Releasesthe lock on an object and blocks the current thread until it reacquires the lock. Syntax: Monitor.Wait(object); Pulse() Method: Notifies a thread in the waiting queue of a change in the locked object's state. Syntax: Monior.Pulse(object);
  • 10.
    Deadlock:  Adeadlock is a situation where an application locks up because two or more activities are waiting for each other to finish. lock(lock1) { lock(lock2) {…} }