一般常用的Thread class來自於 System.Threading。通常Thread會搭配一個需要執行的Function。
1: public void Hello()
2: {
3: Console.WriteLine("Hello World");
4: }
5:
6: Thread tt = new Thread(new ThreadStart(Hello)); //指派Hello方法
7: tt.Start(); //開始執行Thread
ThreadStart 指定的方法必須為無參數型態,而ParameterizedThreadStart 則可以指定方法夾帶參數,但只限制一個且型態為 object 。因此需要透過轉換型態方式來達到所需要的參數型態。
1: public void showHello(object obj)
2: {
3: string sz = (string)obj; //unboxing
4: Console.WriteLine("Say Hello " + sz + " !!");
5: }
6:
7: public void Hello()
8: {
9: Thread tt;
10: tt = new Thread(new ParameterizedThreadStart(showHello));
11: tt.Start("Chris"); //boxing
12: Thread.Sleep(2000);
13: tt.Abort();
14: }
1: public class PrintHello
2: {
3: public string name;
4: public void Hello()
5: {
6: Console.WriteLine("Hello " + name + " !!");
7: }
8: }
9:
10: public void Hello2()
11: {
12: Thread tt;
13: PrintHello p = new PrintHello(); // create class
14: tt = new Thread(new ThreadStart(p.Hello)); // use class method
15: p.name = "chris"; // configure parameter
16: tt.Start();
17: Thread.Sleep(2000);
18: tt.Abort();
19: }
沒有留言:
張貼留言