C Sharp Threading Example Naming Thread

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# Threading Example: Naming Thread

You can change or get the name of the thread by using Name property of Thread class. Let's see an example where we are setting and getting names of the threads.

 
  1. using System;  
  2. using System.Threading;  
  3.   
  4. public class MyThread  
  5. {  
  6.     public void Thread1()  
  7.     {  
  8.         Thread t = Thread.CurrentThread;  
  9.         Console.WriteLine(t.Name+" is running");  
  10.     }  
  11. }  
  12. public class ThreadExample  
  13. {  
  14.     public static void Main()  
  15.     {  
  16.         MyThread mt = new MyThread();  
  17.         Thread t1 = new Thread(new ThreadStart(mt.Thread1));  
  18.         Thread t2 = new Thread(new ThreadStart(mt.Thread1));  
  19.         Thread t3 = new Thread(new ThreadStart(mt.Thread1));  
  20.         t1.Name = "Player1";  
  21.         t2.Name = "Player2";  
  22.         t3.Name = "Player3";  
  23.         t1.Start();  
  24.         t2.Start();  
  25.         t3.Start();  
  26.     }  
  27. }  

Output:

Player1 is running
Player2 is running
Player3 is running