(转)一步一步学习C#中的多线程 --- 1、初识线程(2)--给线程传递参数
一步一步学习C#中的多线程 --- 1、初识线程(2)--给线程传递参数
给线程传递参数的三种方法
1、一种方式是使用ParameterizedThreadStart委托参数的Thread构造函数。参看如下代码:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading;
6: using System.Threading.Tasks;
7: namespace PassDataToThread
8: {
9: class Program
10: {
11: static void Main(string[] args)
12: {
13: Thread t1 = new Thread(printMessage);//省略写法
14: Thread t2 = new Thread(new ParameterizedThreadStart(printMessage));//完整写法
15: t1.Start("Hello MultThread!!");//传递参数
16: t2.Start("Hello MuttThread");//传递参数
17: Console.ReadKey();
18: }
19:
20: static void printMessage(Object message)
21: {
22: string strMessage = (string)message;
23: Console.WriteLine(strMessage);
24: }
25: }
26: }
27:
28:
注意: ParameterizedThreadStart
传递参数个数有限制,只能接收一个参数,并且由于其类型为object,通常需要转型。
2、使用Lambda表达式或匿名函数传递参数。参看如下代码:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading;
6:
7: namespace PassDataToThread
8: {
9: class Program
10: {
11: static void Main(string[] args)
12: {
13: Thread t1 = new Thread(() => Print("Hello Lambda Thread"));//通过Lambda传递参数
14: t1.Start();
15:
16: Thread t2 = new Thread(delegate(){Print("Hello Delegate Method");});//通过匿名函数传递参数
17: t2.Start();
18: }
19: static void Print(string message) {
20: Console.WriteLine(message);
21: Console.ReadKey();
22: }
23: }
24: }
25:
26:
其实如果你查看编译后的代码会发现,这两种方法底层的实现方法是和第一种方法一致的。
3、定义一个类,将线程的主方法定义为类的一个实例方法。这样你就可以给Thread的构造函数传递对象和ThreadMain()方法。线程就可以访问数据了。
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading;
6:
7: namespace PassDataToThread2
8: {
9: class Program
10: {
11: static void Main(string[] args)
12: {
13: MyThread mt = new MyThread("HelloWorld");
14: Thread t1 = new Thread(mt.ThreadMain);
15: t1.Start();
16: Console.ReadKey();
17: }
18: }
19:
20: class MyThread
21: {
22: private string message;
23: public MyThread(string message)
24: {
25: this.message = message;
26: }
27: public void ThreadMain()
28: {
29: Console.WriteLine(message);
30: }
31: }
32: }