c# thread数线程的创建

1、

1

2

3

4

5

6

Thread thread =newThread(newThreadStart(getpic));

thread.Start();

privatevoidshowmessage()

{

Console.WriteLine("hello world");

}

2、带一个参数的线程

使用ParameterizedThreadStart,调用 System.Threading.Thread.Start(System.Object) 重载方法时将包含数据的对象传递给线程。

注意传递的参数只能是object类型,不过可以进行强制类型转换。

1

2

3

4

5

6

7

8

Thread thread =newThread(newParameterizedThreadStart(showmessage));

stringo ="hello";

thread.Start((object)o);

privatestaticvoidshowmessage(objectmessage)

{

stringtemp = (string)message;

Console.WriteLine(message);

}

3、带两个及以上参数的线程

这时候可以将线程执行的方法和参数都封装到一个类里边,通过实例化该类,方法就可以调用属性来尽享传递参数。

例如如下程序,想传入两个string变量,然后打印输出。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

publicclassThreadTest

{

privatestringstr1;

privatestringstr2;

publicThreadTest(stringa,stringb)

{

str1 = a;

str2 = b;

}

publicvoidThreadProc()

{

Console.WriteLine(str1 + str2);

}

}

publicclassExample {

publicstaticvoidMain()

{

ThreadTest tt =newThreadTest("hello ","world");

Thread thread =newThread(newThreadStart(tt.ThreadProc));

thread.Start();

}

}

除了使用类还可以用hashtable、list、dictionary 等集合来传参 ,在方法里进行强制转换。