使用委托进行异步编程

1.什么是异步编程
常常迷惑于什么是异步编程,到底有什么好处.使用 .NET 异步编程,在程序继续执行的同时对 .NET 类方法进行调用,直到进行指定的回调为止;如果没有提供回调,则直到对调用的阻塞、轮询或等待完成为止。例如,一个程序可以调用一个方法,该方法枚举一个较大的列表,同时主程序将继续执行。在完成枚举后,进行回调并由程序对它进行寻址。
2.异步委托编程
异步委托提供以异步方式调用同步方法的能力.如果调用"BeginInvoke"方法,则公共语言运行库(CLR)将对请求进行排队并立即返回到调用方.将对来自线程池的线程调用该目标方法.提交请求的原始线程自由地继续与目标方法并行执行,该目标方法是对线程池线程运行的.我迷惑的地方是线程池的线程及目标方法.
下边来看下小例子.Example1

 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4using System.Threading;
 5
 6namespace AsyncDelegate
 7{
 8    class AsyncMethod
 9    {
10        public delegate void AsyncEventHandler();
11
12        public void Event1()  //委托的目标方法
13        {
14            Console.WriteLine("Event1 Start");
15            Thread.Sleep(2000);
16            Console.WriteLine("Thread id is " + Thread.CurrentThread.ManagedThreadId); 
17            Console.WriteLine("Event1 End");
18        }

19
20        public void Event2()
21      {
22            Console.WriteLine("Event2 Start");
23            Thread.Sleep(2000);
24            Console.WriteLine("Event2 End");
25        }

26
27        public static void Main()
28       {
29            AsyncMethod am = new AsyncMethod();
30            long start = 0;
31            long end = 0;
32            Console.WriteLine("Read go");
33            start = DateTime.Now.Ticks;
34            am.Event1();
35            am.Event2();
36            Console.WriteLine("Main id is " + Thread.CurrentThread.ManagedThreadId);
37
38            end = DateTime.Now.Ticks;
39
40             Console.WriteLine("时间刻度差="+ Convert.ToString(end-start) );
41             Console.ReadLine();
42
43        }

44    }

45}

46

其输出为:
Read go
Event1 Start
Thread id is 10
Event1 end
Event2 start
Event2 End
Main id is 10
时间刻度差=40000000

我们可以看到运行的时间=Event1+Event2的时间.
我们把32--36之间的代码改为如下Example2
1AsyncEventHandler c1 = new AsyncEventHandler(am.Event1);
2            Console.WriteLine("Read go");
3            start = DateTime.Now.Ticks;
4            IAsyncResult result = c1.BeginInvoke(nullnull);
5            am.Event2();
6            Console.WriteLine("Main id is " + Thread.CurrentThread.ManagedThreadId);
7            c1.EndInvoke(result);


其运行结果如下:
Read go
Event2 Start
Event1 Start
Event2 End
Main id is 10
Thread id is 7
Event1 End
时间刻度差=20000000

由此我们可以看出Event1与Event2是运行在不同的线程上."将对来自线程池的线程调用该目标方法."线程池的线程就是7线程,而目标方法Event1就运行在此线程上.这个总的运行时间(Example2)是远远小于Example1的.
先写在这里,阻止线程运行等以后写.
感谢http://www.cnblogs.com/aierong/archive/2005/05/25/162308.html Mcad的例子的提醒.

3.委托回调的例子Example3

 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4using System.Threading;
 5using System.Runtime.Remoting.Messaging;
 6
 7namespace AsyncDelegate
 8{
 9    public class DelegateMethod
10    {
11        public static short AddMethod(ref int param1,ref int param2) //委托方法
12        {
13            Console.WriteLine("DelegateMethod Start");
14            Thread.Sleep(2000);
15            Console.WriteLine("The delegateMethod thread id is {0} ",Thread.CurrentThread.ManagedThreadId);
16            if (param1 > 10000)
17            {
18                param1 = 3000;
19            }

20            if (param2 > 10000)
21            {
22                param2 = 4000;
23            }

24            Console.WriteLine("DelegateMethod End");
25            return (short)(param1 + param2);
26        }

27    }

28
29    public delegate short AsyncDelegate(ref int param1,ref int param2);
30
31    class AsyncMethod
32    {
33        ManualResetEvent waiter;
34
35        public void CallBackMethod(IAsyncResult result) //回调方法
36        {
37            Console.WriteLine("CallBackMethod start");
38            Thread.Sleep(2000);
39            int param1 = 0;
40            int param2 = 0;
41            AsyncDelegate caller = (AsyncDelegate)((AsyncResult)result).AsyncDelegate;
42
43            int add = (int)result.AsyncState;
44
45            short addResult = caller.EndInvoke(ref param1, ref param2, result);
46            Console.WriteLine("The CallBackMethod's thread id is {0}", Thread.CurrentThread.ManagedThreadId);
47            Console.WriteLine("The param1 is {0} and the param2 is {1},the add's result is {2}. The object is {3}",
48                param1,param2,addResult,add);
49            Console.WriteLine("CallBackMethod end");
50            waiter.Set();
51        }

52
53        public void Call()
54        {
55            AsyncDelegate asyncDelegate = new AsyncDelegate(DelegateMethod.AddMethod);
56
57            int param1 = 10000;
58            int param2 = 10000;
59            
60            int temp = 60000; //此对应CallBackMethod的int add = (int)result.AsyncState;

61            waiter = new ManualResetEvent(false);
62
63            AsyncCallback callBack = new AsyncCallback(this.CallBackMethod);
64
65            IAsyncResult result = asyncDelegate.BeginInvoke(ref param1, ref param2, callBack, temp);
66            waiter.WaitOne();
67        }

68
69        public void Event2()
70        {
71            Console.WriteLine("Event2 Start");
72            Thread.Sleep(2000);
73            Console.WriteLine("Event2 End");
74        }

75        public static void Main()
76        {
77            Console.WriteLine("Main thread start");
78            long start = 0;
79            long end = 0;
80            start = DateTime.Now.Ticks;
81            Console.WriteLine("Main thread id is {0} ",Thread.CurrentThread.ManagedThreadId);
82            AsyncMethod asyncMethod = new AsyncMethod();
83            asyncMethod.Call();
84            asyncMethod.Event2();
85            Console.WriteLine("Main thread end");
86            end = DateTime.Now.Ticks;
87            Console.WriteLine("时间刻度差是:{0} ",end - start);
88            Console.ReadKey();
89        }

90    }

91}

92

其输出为:
Main thread start
Main thread id is 10
DelegateMethod Start
The delegateMethod thread id is 11
DelegateMethod End
CallBackMethod start
the callBackMethod's thread id is 11
The param1 is 10000 and the param2 is 10000the add's result is 20000.....
CallBackMethod end
Event2 start
Event2 end
Main thread end
时间刻度查是:60000000

可以看出,委托回调里调用EndInvoke是阻止主线程运行的.也就是说主线程要等BeginInvoke的线程执行完才执行.
而回调方法的线程和委托方法的线程在一个线程上.
.....继续研究中
 

posted @ 2007-04-19 10:50  Kuffy Wang  阅读(705)  评论(0编辑  收藏  举报