Knowledge Management Banner

Knowledge Management Banner

C# : Process , Thread , Thread Join, Parameterized Thread: Part 29

What is process ?
  • The execution of program by providing the required resource required, is called process.
Thread
  • A process can be said as thread. A process at least has one main thread. A single process can have multiple thread
Advantage of multi thread
  • to maintain responsive user interface
  • to make efficient use of processor time
  • to split large task
Disadvantage of multi thread
  • On single processor threading can affect the performance
  • Need to write multiple line of codes.
  • Multi thread application are difficult to write, debug and understand.
Parameterized Thread

 namespace ThreadParameterized  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       DemoClass objDemo = new DemoClass();  
       ParameterizedThreadStart ThreadParam = new ParameterizedThreadStart(objDemo.AddNumber);  
       Thread demoThread = new Thread(ThreadParam);  
       demoThread.Start(2);  
     }  
   }  
   public class DemoClass  
   {  
     public void AddNumber(object Num)  
     {  
       Console.WriteLine("result is : " + (10 + int.Parse(Num.ToString())));  
     }  
   }  
 }  

Thread Join

  • In the example below as soon as t1.join() is executed main thread waits for thread t1 to complete.
  • When t2.join() is executed, main thread waits for thread t2 to get executed.
  • After these two the main thread will be completed


 namespace ThreadJoin  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       DemoClass obj = new DemoClass();  
       Thread t1 = new Thread(obj.Print1);  
       t1.Start();  
       Thread t2 = new Thread(obj.Print2);  
       t2.Start();  
       t1.Join();  
       Console.WriteLine("thread 1 completed");  
       t2.Join();  
       Console.WriteLine("thread 2 completed");  
       Console.WriteLine("Main thread completed");  
     }  
   }  
   public class DemoClass  
   {  
     public void Print1()  
     {  
       Console.WriteLine("Print 1 function");  
     }  
     public void Print2()  
     {  
       Console.WriteLine("Print 2 function");  
     }  
   }  
 }  

No comments

Powered by Blogger.