如果方法有参数的话,我们就需要ParameterizedThreadStart,转到定义可以看出ParameterizedThreadStart是一个委托,参数类型必须是Object类型。
可以用线程的Start方法传入参数。
static void Worker(object data)
{
Thread.Sleep(1000);
Console.WriteLine("传入的参数是:"+data.ToString());
Console.WriteLine("后台线程退出");
}
static void Main(string[] args)
{
Thread thread1 = new Thread(new ParameterizedThreadStart(Worker));
thread1.Start(123);
Console.WriteLine("主线程退出");
Console.ReadKey();
}
如果需要传递多个参数的话,我们可以传入一个数组或集合。
static void Worker1(object data)
{
List<int> list = (List<int>)data;
Thread.Sleep(1000);
for(int i = 0; i < list.LongCount(); i++)
{
Console.WriteLine(list[i]);
Console.WriteLine("后台线程退出");
}
}
static void Main(string[] args)
{
//Thread thread1 = new Thread(new ParameterizedThreadStart(Worker));
List<int> list = new List<int> { 1, 2, 3 };
Thread thread1 = new Thread(new ParameterizedThreadStart(Worker1));
thread1.Start(list);
Console.WriteLine("主线程退出");
Console.ReadKey();
}