Passing an argument to the thread method. : Thread Creation « Thread « C# / CSharp Tutorial






using System;  
using System.Threading;  
  
class MyThread {  
  public int count;  
  public Thread thrd;  
 
  public MyThread(string name, int num) {  
    count = 0;  
 
    thrd = new Thread(new ParameterizedThreadStart(this.run)); 
 
    thrd.Name = name; 
 
    thrd.Start(num);  
  }  
  
  void run(object num) {  
    Console.WriteLine(thrd.Name + " starting with count of " + num);  
  
    do {  
      Thread.Sleep(500);  
      Console.WriteLine("In " + thrd.Name + ", count is " + count);  
      count++;  
    } while(count < (int) num);  
  
    Console.WriteLine(thrd.Name + " terminating.");  
  }  
}  
  
class MainClass {  
  public static void Main() {  
    MyThread mt = new MyThread("Child #1", 5);  
    MyThread mt2 = new MyThread("Child #1", 3);  
  
    do {  
      Thread.Sleep(100);  
    } while (mt.thrd.IsAlive | mt2.thrd.IsAlive);  
  
    Console.WriteLine("Main thread ending.");  
  }  
}
Child #1 starting with count of 5
Child #1 starting with count of 3
In Child #1, count is 0
In Child #1, count is 0
In Child #1, count is 1
In Child #1, count is 1
In Child #1, count is 2
In Child #1, count is 2
Child #1 terminating.
In Child #1, count is 3
In Child #1, count is 4
Child #1 terminating.
Main thread ending.








20.1.Thread Creation
20.1.1.Thread method with parameter
20.1.2.Thread method with no parameter
20.1.3.The creation of threads
20.1.4.Create a thread of execution
20.1.5.Create multiple threads of execution
20.1.6.Passing an argument to the thread method.
20.1.7.Use anonymous delegate as the worker method to create Thread
20.1.8.Adding with Thread objects
20.1.9.Communicating Data to a Thread
20.1.10.Primary Thread statistcs
20.1.11.Starting a Method in a Separate Thread
20.1.12.Thread Stats
20.1.13.List threads for PID