你的位置:首页 > ASP.net教程

[ASP.net教程]C# 线程传参


传参方式有两种:

       1、创建带参构造方法类 传参

       2、利用Thread.start(8)直接传参,该方法会接收一个对象,并将该对象传递给线程,因此在线程中启动的方法

             必须接收object类型的单个参数。

       3、闭包传参 该方法使用lambda表达式。

           3.1 lambda表达式中使用任何局部变量时 ,C# 会自动生成一个类,并将该变量作为该类的一个属性。实际上与第一种方式基本一样,但是我们无需定义类,C#会自动编译实现该类。

           3.2 使用lambda表达式会导致一些问题,如使用多个lambda表达式中使用相同的变量,他们会共享该变量值

 

          

using System;using System.Threading;namespace testThread_Transferparameters{  class Program  {    static void Main(string[] args)    {            //1      var sample = new ThreadSample(10);      var threadone = new Thread(sample.CountNumbers);      threadone.Name = "ThreadOne";      threadone.Start();      threadone.Join();      Console.WriteLine("------------------");             //2      var threadtwo = new Thread(count);      threadtwo.Name = "threadtwo";      threadtwo.Start(8);      threadtwo.Join();      Console.WriteLine("------------------");             //3      var threadthree = new Thread(() => CountNumbers(20));      threadthree.Name = "threadthree";      threadthree.Start();      threadthree.Join();      Console.WriteLine("------------------");      int i = 10;      var threadfour = new Thread(() => PrintNumber(i));      i = 20;      var threadfive = new Thread(() => PrintNumber(i));      threadfour.Start();      threadfive.Start();    }    static void count(object iterations)    {      CountNumbers((int)iterations);    }    static void CountNumbers(int iterations)    {      for (int i = 1; i <= iterations; i++)      {        Thread.Sleep(TimeSpan.FromSeconds(0.5));        Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);      }    }    static void PrintNumber(int number)    {      Console.WriteLine(number);    }  }  class ThreadSample  {    private readonly int _iterations;    public ThreadSample(int iterations)    {      _iterations = iterations;    }    public void CountNumbers()    {      for (int i = 1; i <= _iterations; i++)      {        Thread.Sleep(TimeSpan.FromSeconds(0.5));        Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);      }    }  }}

 结果如下: