C# 使用自定义线程类向线程传递参数

C# 中的线程 Thread的定义与使用:

1.默认是需要传一个无返回值无参数的方法:void Func();

Thread th = new Thread(Func);

th.Start();

2.默认的向线程中传值,使用的是 ParameterizedThreadStart(Object obj).,无返回值 。它传入的是一个 Object类型的参数。 void Func(Object obj);

Thread th = new Thread(new ParameterizedThreadStart(Func));
th.Start(something);

3.我们可以使用一个类把线程封装起来,这样传什么参数,会自由方便得多。

示例代码:

  

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 
 7 namespace ThreadTest
 8 {
 9     // 定义一个 封装纯种的抽象类
10     // 1.需要定义一个Thread。
11     // 2.一个需要让了类重写的 抽象方法: run,(线程具体的工作)
12     // 3.一个开始线程的方法 Start.
13     abstract class MyThread
14     {
15         public Thread thr = null;
16         public abstract void run();
17         public void Start() {
18             if (thr == null) {
19                 thr = new Thread(run);
20                 thr.Start();
21             }
22         }
23     }
24 
25     // 定义一个 类 ,继承自 封装线程类
26     // 可以随意的增加字段或属性(也就是相当于向线程里传参数)
27     class Test : MyThread
28     {
29         private string name;
30         private int age;
31         public Test(string s, int i) {
32             name = s;
33             age = i;
34         }
35         // 重写 run 方法 
36         public override void run() {
37             Console.WriteLine("My name is " + name + " and " + age.ToString() + " years old.");
38         }
39     }
40 
41     class Program
42     {
43         static void Method(object s) {
44             Console.WriteLine(s);
45         }
46 
47         static void Main(string[] args) {
48             // 使用线程类
49             Test t = new Test("zhoutianchi", 30);
50             t.Start();
51             // 使用普通的线程传参数 ParameterizedThreadStart(Object obj).
52             Thread t1 = new Thread(new ParameterizedThreadStart(Method));
53             t1.Start("zhoutianchi,liuxiaolin,zhouqihan");
54 
55             Console.ReadKey();
56         }
57     }
58 }
原文地址:https://www.cnblogs.com/easyfrog/p/2762873.html