Saturday, 7 May 2011

Threads in C#

What is thread ?
Threads are typically created when you want a program to do two things at once.
Starting Threads
The simplest way to create a thread is to create a new instance of the Thread class. The Thread constructor takes a single argument: a
delegate type. The CLR provides the ThreadStart delegate class specifically for this purpose, which points to a method you designate.
This allows you to construct a thread and to say to it "when you start, run this method." The ThreadStart delegate declaration is:-

         public delegate void ThreadStart( );
Example for Creating Thread:

using System;
using System.Threading;
  public class CreatingThread
  {
    static void Main(string[] args)
    {
      Thread MyThread = new Thread(new ThreadStart(ThreadProc));

      MyThread.Start();
      MyThread.Join();
    }
    protected static void ThreadProcess()
    {
      for (int i = 0; i < 100; i++)
      {
        Console.WriteLine(i);
      }
    }
  }
Creating a Thread of Execution:

using System; 
using System.Threading; 
class MyThread
 { 
  public int count; 
  string thrdName; 
  public MyThread(string name) { 
  count = 0; 
  thrdName = name; 
  } 
 public void run() 
    { 
         Console.WriteLine(thrdName + " starting."); 
 
        do { 
            Thread.Sleep(500); 
            Console.WriteLine("In " + thrdName +", count is " + count); 
            count++; 
           } while(count < 10);  
         Console.WriteLine(thrdName + " terminating."); 
       } 
  } 
 public class MultiThread 
   { 
   public static void Main() 
    { 
            Console.WriteLine("Main thread starting."); 
            MyThread mt = new MyThread("Child #1"); 
            Thread newThrd = new Thread(new ThreadStart(mt.run)); 
            newThrd.Start(); 
         do { 
              Console.Write("."); 
              Thread.Sleep(100); 
            } while (mt.count != 10); 
            Console.WriteLine("Main thread ending."); 
   } 
 }           
Joining Threads
To join thread1 (t1) onto thread2 (t2), write:
    t2.Join( );
Joining the current thread to each thread in the collection in turn:
 

foreach (Thread myThread in myThreads)
{
myThread.Join( );
}
Console.WriteLine("All my threads are done.");
Create multiple threads of execution

using System; 
using System.Threading; 
class MyThread
{ 
  public int count; 
  public Thread thrd; 
  public MyThread(string name)
  { 
    count = 0; 
    thrd = new Thread(new ThreadStart(this.run)); 
    thrd.Name = name; 
    thrd.Start(); 
  } 
  void run() 
 { 
    Console.WriteLine(thrd.Name + " starting."); 
     do 
 { 
      Thread.Sleep(500); 
      Console.WriteLine("In " + thrd.Name +", count is " + count); 
      count++; 
    } while(count < 10); 
     Console.WriteLine(thrd.Name + " terminating."); 
  } 
} 
public class MoreThreads { 
  public static void Main() { 
    Console.WriteLine("Main thread starting."); 
    MyThread mt1 = new MyThread("Child #1"); 
    MyThread mt2 = new MyThread("Child #2"); 
    MyThread mt3 = new MyThread("Child #3"); 
    do 
 { 
      Console.Write("."); 
      Thread.Sleep(100); 
    } while (mt1.count < 10 || mt2.count < 10 || mt3.count < 10); 
     Console.WriteLine("Main thread ending."); 
  } 
}
Suspending Threads
To cause your thread to sleep for one second, you can invoke the static method of Thread, Sleep, which suspends the thread in which it is
invoked:
                   Thread.Sleep(1000);
 

Killing Threads
For killing a thread Abort( ) method is used. This causes a ThreadAbortException exception to be thrown, which the thread can catch,
and thus provides the thread with an opportunity to clean up any resources it might have allocated.
catch (ThreadAbortException)
{
Console.WriteLine("[{0}] Aborted! Cleaning up...",
Thread.CurrentThread.Name);
}
Example for Suspending, resuming, and stopping a thread:

using System; 
using System.Threading; 
class MyThread {  
  public Thread thrd;  
  public MyThread(string name) {  
    thrd = new Thread(new ThreadStart(this.run)); 
    thrd.Name = name; 
    thrd.Start();  
  }  
  void run() {  
    Console.WriteLine(thrd.Name + " starting."); 
    for(int i = 1; i <= 1000; i++) {  
      Console.Write(i + " ");  
      if((i%10)==0) { 
        Console.WriteLine(); 
        Thread.Sleep(250); 
      } 
    } 
    Console.WriteLine(thrd.Name + " exiting.");  
  }  
} 
public class SuspendResumeStop {  
  public static void Main() {  
    MyThread mt1 = new MyThread("My Thread");  
    Thread.Sleep(1000); // let child thread start executing 
    mt1.thrd.Suspend();  
    Console.WriteLine("Suspending thread.");  
    Thread.Sleep(1000); 
    mt1.thrd.Resume();  
    Console.WriteLine("Resuming thread.");  
    Thread.Sleep(1000); 
    mt1.thrd.Suspend();  
    Console.WriteLine("Suspending thread.");  
    Thread.Sleep(1000); 
    mt1.thrd.Resume();  
    Console.WriteLine("Resuming thread.");  
    Thread.Sleep(1000); 
    Console.WriteLine("Stopping thread.");  
    mt1.thrd.Abort(); 
    mt1.thrd.Join(); // wait for thread to terminate 
    Console.WriteLine("Main thread terminating.");  
  }  
}
Synchronization
Synchronization is provided by a lock on the object, which prevents a second thread from barging in on your
object until the first thread is finished with it.

No comments:

Post a Comment