happyhippy

这个世界的问题在于聪明人充满疑惑,而傻子们坚信不疑。--罗素

 1namespace 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(1020,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(1020nullnull);
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(1020nullnull);
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(1020new 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
86Question6.TestAsyn1();
87Question6.TestAsyn2();
88Question6.TestAsyn3();
89Question6.TestAsyn4();
90Console.WriteLine("Press any Key to Continue");
91Console.ReadLine();
92
posted on 2007-07-23 10:07  Silent Void  阅读(528)  评论(0编辑  收藏  举报