1
namespace
Bingosoft.Training2007.CSharp
2
{
3
delegate int Sum(int num1,int num2);
4
/**//// <summary>
5
/// 使用Delegate的BeginInvoke方法完成一个函数的异步调用过程。
6
/// </summary>
7
class Question6
8
{
9
/**//// <summary>
10
/// 求两个int型数的和(仅供演示)
11
/// </summary>
12
/// <param name="num1"></param>
13
/// <param name="num2"></param>
14
/// <returns></returns>
15
public static int GetSum(int num1, int num2)
16
{
17
Thread.Sleep(1000);
18
return num1 + num2;
19
}
20
21
/**//// <summary>
22
/// 用EndInvoke等待异步调用
23
/// </summary>
24
public static void TestAsyn1()
25
{
26
Sum sum = new Sum(GetSum);
27
IAsyncResult result = sum.BeginInvoke(10, 20,null,null);
28
Console.WriteLine("计算中
");
29
int returnVal = sum.EndInvoke(result);
30
Console.WriteLine(returnVal);
31
}
32
33
/**//// <summary>
34
/// 用WaitHandle等待异步调用
35
/// </summary>
36
public static void TestAsyn2()
37
{
38
Sum sum = new Sum(GetSum);
39
IAsyncResult result = sum.BeginInvoke(10, 20, null, null);
40
result.AsyncWaitHandle.WaitOne();
41
Console.WriteLine("计算完毕:");
42
int returnVal = sum.EndInvoke(result);
43
Console.WriteLine(returnVal);
44
}
45
46
/**//// <summary>
47
/// 轮训查询等待异步调用
48
/// </summary>
49
public static void TestAsyn3()
50
{
51
Sum sum = new Sum(GetSum);
52
IAsyncResult result = sum.BeginInvoke(10, 20, null, null);
53
while (!result.IsCompleted)
54
{
55
Console.WriteLine("计算中
");
56
}
57
int returnVal = sum.EndInvoke(result);
58
Console.WriteLine(returnVal);
59
}
60
61
/**//// <summary>
62
/// 异步调用完成后,执行回调
63
/// </summary>
64
public static void TestAsyn4()
65
{
66
Sum sum = new Sum(GetSum);
67
IAsyncResult result = sum.BeginInvoke(10, 20, new AsyncCallback(Question6.CallBackAsyn), sum);
68
Console.WriteLine("计算中
");
69
}
70
71
/**//// <summary>
72
/// 回调函数
73
/// </summary>
74
/// <param name="ar"></param>
75
public static void CallBackAsyn(IAsyncResult ar)
76
{
77
Sum sum = (Sum)ar.AsyncState;
78
int returnVal = sum.EndInvoke(ar);
79
MessageBox.Show(returnVal.ToString(), "计算结果:", MessageBoxButtons.OK, MessageBoxIcon.Information);
80
}
81
}
82
}
83
84
85
//
测试Question6
86
Question6.TestAsyn1();
87
Question6.TestAsyn2();
88
Question6.TestAsyn3();
89
Question6.TestAsyn4();
90
Console.WriteLine(
"
Press any Key to Continue
"
);
91
Console.ReadLine();
92

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



66

67

68


69

70

71


72

73

74

75

76



77

78

79

80

81

82

83

84

85

86

87

88

89

90


91

92
