前一节说了我们创建线程的参数是一个函数,当新的线程启动的时候,它就会执行这个函数,这个函数是没有任何参数的,且没有返回值的,那么新的需求来了,如何调用一个有参数的函数呢?
利用构造函数传递参数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace _2_ThreadArgs
{
class Program
{
static void Main(string[] args)
{
MyCustomClass myclass = new MyCustomClass("我是参数字符串啊");
Thread thread = new Thread(new ThreadStart(myclass.Worker));
thread.Start();
thread.Join(Timeout.Infinite);
}
}
/// <summary>
/// 我们构造一个类
/// </summary>
class MyCustomClass
{
private string _args;
public MyCustomClass(string strArg)
{
_args = strArg;
}
public void Worker()
{
Console.WriteLine("参数输入为:" + _args);
}
}
}
运行机制
首先我们构造一个类MyCustomClass,这个类是带参数的,且是输入一个字符串,然后通过构造函数保存在一个类成员变量中,另外还有一个Worker()方法是输出一句话。我们先构造一个类,然后把这个类的方法Worker()作为ThreadStart()的参数,就是利用构造函数传递参数。
运行效果