C# 线程调用带参数的方法
示例1:以类实现
class Program
{
static void Main(string[] args)
{
Test test = new Test("线程调用带参数的方法", "轻松搞定");
Thread thread = new Thread(new ThreadStart(test.Write));
thread.Start();
}
}
public class Test
{
private string p1;
private string p2;
public Test(string par1,string par2)
{
p1 = par1;
p2 = par2;
}
public void Write()
{
Console.WriteLine(p1);
Console.WriteLine(p2);
}
}
示例2:使用ParameterizedThreadStart //只能带一个object的参数
class Program
{
static void Main(string[] args)
{
Program pro=new Program();
Thread thread = new Thread(new ParameterizedThreadStart(pro.Write2));
thread.Start("线程调用带参数的方法");
}
public void Write2(object par)
{
Console.WriteLine(par);
}
}
示例3:使用静态变量,属性 //慎用
static void Main(string[] args)
{
Program pro=new Program();
Thread thread = new Thread(new ThreadStart(pro.Write3));
thread.Start();
}
public void Write3()
{
Console.WriteLine(Par);
}
public static string Par
{
get
{
return "线程调用带参数的方法";
}
}