C#线程传参的方法总结
方式1 委托
使用线程自带的委托传参,示例如下:
static void Main(string[] args)
{
string str = "你好";
Thread th = new Thread(OnThread);
th.Start(str);
Console.Read();
}
static void OnThread(object o)
{
string str = o as string;
if (!string.IsNullOrEmpty(str))
Console.WriteLine(str);
}
注意:使用这种方法传递的参数必须是object类型的,而且需要进行类型转换。
方式2 lambda表达式
相比方式1,使用此方法的好处就是不要进行参数的类型转换,示例如下:
static void Main(string[] args)
{
string str = "哈喽啊";
Thread th = new Thread(() => OnThread(str));
th.Start();
Console.Read();
}
static void OnThread(string str)
{
Console.WriteLine(str);
}
方式3 自定义类
需要定义一个类,在类中定义需要的字段,将线程的主方法定义为类的一个实例方法,让线程去运行自定义类的实例方法,示例如下:
static void Main(string[] args)
{
MyThread myThread = new MyThread("在干嘛");
Thread th = new Thread(myThread.ThreadMain);
th.Start();
Console.Read();
}
}
public class MyThread
{
private string _str;
public MyThread(string param)
{
this._str = param;
}
public void ThreadMain()
{
Console.WriteLine(_str);
}
}
方式4 多参数传递
1、 将参数作为数组或者集合传入
此方法传递的多个参数,如果是同类型的,可以用数组或者是List<>传入线程;如果是不同类型的,可以用object[]或者List传入,示例如下:
(1)同类型参数
static void Main(string[] args)
{
string[] strs = new string[3] { "你好", "哈喽", "嗨" };
Thread th = new Thread(OnThread);
th.Start(strs);
Console.Read();
}
static void OnThread(object o)
{
string[] strs = o as string[];
Console.WriteLine("打招呼的三种方式: {0} {1} {2}", strs[0], strs[1], strs[2]);
}
(2)不同类型参数
static void Main(string[] args)
{
List<object> list = new List<object>();
list.Add("球衣号码:");
list.Add("7");
Thread th = new Thread(OnThread);
th.Start(list);
Console.Read();
}
static void OnThread(object o)
{
List<object> list = o as List<object>;
Console.WriteLine("{0}{1}", list[0], list[1]);
}
2、自定义类传递多参数
利用上述方式3传递多个参数,不论参数类型是否相同都可使用此方法,示例如下:
class Program
{
static void Main(string[] args)
{
MyThread myTh = new MyThread();
myTh.IntParam = 7;
myTh.Str = "球衣号码是:";
Thread th = new Thread(myTh.ThreadMain);
th.Start();
Console.Read();
}
static void OnThread(object o)
{
List<object> list = o as List<object>;
Console.WriteLine("{0}{1}", list[0], list[1]);
}
}
public class MyThread
{
private string _str;
private int _int;
public string Str
{
set { _str = value; }
}
public int IntParam
{
set { _int = value; }
}
public MyThread()
{
}
public void ThreadMain()
{
Console.WriteLine("{0}{1}", _str, _int);
}
}