1
using System;
2
using System.Threading;
3
4
namespace ifan
5
{
6
//自定义委托声明
7
public delegate void childExitDelegate(object sender, ChildExitEventArgs e);
8
9
public class TDelegate
10
{
11
//自定义的事件,实际上就是上面那个委托类型的实例
12
public static event childExitDelegate onChildThreadExit;
13
14
private static void 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事件的方法
29
private static void 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
37
private static void 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
//自定义事件参数
51
public class ChildExitEventArgs : EventArgs
52
{
53
private string child_name_cn;
54
55
public string 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
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65
