ThreadStart和ParameterizedThreadStart的区别

ThreadStart:所执行的方法不能有参数(不需要传递参数,也不需要返回参数)

启动一个线程最直观的办法是使用Thread类,具体步骤如下:

class Program
{
  static void Main(string[] args)
  {

      ThreadStart threadStart = new ThreadStart(Calculate);
      Thread thread = new Thread(threadStart);
     //以上两句可以合成一句 Thread thread = new Thread(new ThreadStart(Calculate));
     thread.Start();
     Console.ReadKey();

  public static void Calculate()
  {
    double Diameter = 0.5;
    Console.WriteLine("The Area Of Circle with a Diameter of {0} is {1}", Diameter, Diameter * Math.PI);
  }
}

运行结果:

上面我们定义了一个ThreadStart类型的委托,这个委托制定了吸纳成需要执行的方法:Calculate,在这个方法中计算一个直径为0.5的圆的周长并输出。这就构成了简单的多线程的例子。

ThreadStart

的定义:

public void Start()

也就是说,所执行的方法不能有参数,这显然是个很大的不足,为了弥补这个缺陷,.Net为了解决这个问题二设定的另一个委托就是ParameterizedThreadStart

ParameterizedThreadStart:所执行的方法可以带单个参数

ParameterizedThreadStart的定义为:

public delegate void ParameterizedThreadStart(
	Object obj
)

使用这个委托定义的线程的启动函数可以接受一个输入参数,具体例子如下:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("****Adding with Thread objects****");
        Console.WriteLine("ID of thread in Main():{0}", Thread.CurrentThread.ManagedThreadId);

        AddParameters ap = new AddParameters(10, 10);
        Thread t = new Thread(new ParameterizedThreadStart(Add));
        t.Start(ap);
        Console.ReadKey();
    }
    public static void Calculate(object arg)
    {
         double Diameter = (double)arg;
         Console.WriteLine("The Area Of Circle with a Diameter of {0} is {1}", Diameter, Diameter * Math.PI);
     }
     static void Add(object data)
     {
        if(data is AddParameters)
        {
            Console.WriteLine("ID of thread in Add():{0}", Thread.CurrentThread.ManagedThreadId);
            AddParameters ap = (AddParameters)data;
            Console.WriteLine("{0} + {1} is {2}", ap.a, ap.b, ap.a + ap.b);
        }
    }
}
    class AddParameters
    {
        public int a, b;
        public AddParameters(int numb1, int numb2)
        {
            a = numb1;
            b = numb2;
        }
    }

Calculate方法有一个为object类型的参数,虽然只有一个参数,而且还是object类型的,使用的时候尚需要类型转换,但是已经可以有参数了,并且通过把多个参数组合到一个类中,然后把这个类的实例作为参数传递,就可以实现多个参数传递。

运行结果:

 

 

 

 

  

 

 

 

 

 

posted @ 2015-05-05 13:18  刘翠翠  阅读(273)  评论(0)    收藏  举报