多线程通信实例(子线程向主线程:用委托事件实现)
1using System;
2using System.Threading;
3
4namespace ifan
5{
6 //自定义委托声明
7publicdelegatevoid childExitDelegate(object sender, ChildExitEventArgs e);
8
9 publicclass TDelegate
10 {
11 //自定义的事件,实际上就是上面那个委托类型的实例
12publicstaticevent childExitDelegate onChildThreadExit;
13
14 privatestaticvoid Main()
15 {
16 //订阅事件,就是说,当onChildThreadExit事件发生时调用onChildExitFunction方法
17 onChildThreadExit += onChildExitFunction;
18
19 //产生一个子线程,ParameterizedThreadStart可以带一个object参数,所以2.0之后我都用这个很方便
20 Thread t =new Thread(new ParameterizedThreadStart(childRunning));
21 t.Name ="子线程1";
22
23 //在这里,我们将onChildThreadExit事件传递进去
24 //注意,这个事件实际上是委托的实例,也是一个对象
25 t.Start(onChildThreadExit);
26 }
27
28 //一个可以处理onChildThreadExit事件的方法
29privatestaticvoid onChildExitFunction(object sender, ChildExitEventArgs e)
30 {
31 Thread t = (Thread)sender;
32 Console.WriteLine("子线程名称:{0}", t.Name);
33 Console.WriteLine("消息:{0}", e.Child_Name_CN);
34 }
35
36 //子线程入口,注意参数类型只能是object
37privatestaticvoid childRunning(object e)
38 {
39 Thread.Sleep(2000);
40 ChildExitEventArgs msg =new ChildExitEventArgs("子线程已经结束");
41
42 //把传递进来的参数e转换为childExitDelegate委托类型,也就是一个事件
43 childExitDelegate sendEventMessage = (childExitDelegate)e;
44
45 //触发事件,注意我们要遵守约定,传递事件现场的参数
46 sendEventMessage(Thread.CurrentThread, msg);
47 }
48 }
49
50 //自定义事件参数
51publicclass ChildExitEventArgs : EventArgs
52 {
53 privatestring child_name_cn;
54
55 publicstring Child_Name_CN
56 {
57 get{return child_name_cn;}
58 }
59
60 public ChildExitEventArgs(string _child_name_cn)
61 {
62 child_name_cn = _child_name_cn;
63 }
64 }
65}