C# 异步调用的学习 BeginInvoke ManualRestEvent

C# 异步调用的学习 BeginInvoke ManualRestEvent

View Code
 1 using System;
2 using System.Threading;
3
4 class AsyncTest
5 {
6 // 声明一个委托,与你要异步的方法有同样的签名
7 // 其实就是用委托把一个方法包裹了一下.这样就可以
8 // 使用 委托的 IAsyncResult BegionInvoke(AsyncCallback callback,Object object)
9 // 方法实现异步操作
10 public delegate void AsyncEventHandler();
11
12 // 这个ManualRestEvent类可以控制 将一下线程暂停(waitOne) 等待一个(set) 再继续
13 // 如果初始状态处于终止状态,为 true;否则为 false
14 public static ManualResetEvent allDone = new ManualResetEvent(false);
15
16 // 这个方法 就是我们用来异步的方法
17 static void Event1()
18 {
19 Console.WriteLine("Event1 Start");
20 Thread.Sleep(1000);
21 Console.WriteLine("Event1 End");
22 }
23
24 // 这是异步的回调函数.就是执行完了那个函数之后做什么.
25 // 如果什么都不做 是可以省略的.null
26 static void callBack(IAsyncResult ia)
27 {
28 // 在主函数中我们把一个字符串传了进来
29 // 我们 需要还原它
30 string s = (string)ia.AsyncState;
31 Console.WriteLine(s);
32
33 // 执行完后 不要忘了 把ManualRestEvent Set一下
34 // 让主线程继续执行
35 allDone.Set();
36 }
37
38 static void Main()
39 {
40 // 这个 字符串.我们做为一个物体传给 回调函数 让
41 // 回调函数输出它
42 string str = "Hello World";
43
44 // 用我们定义的委托把 那个方法 包裹一下
45 AsyncEventHandler ae = new AsyncEventHandler(AsyncTest.Event1);
46
47 // 使用委托的异步调用方法 如果不需要callback
48 // 可以把参数都设为null , 只是让他去完成这个函数又不阻塞就行了
49 ae.BeginInvoke(callBack,str);
50
51 Console.WriteLine("~~~");
52
53 // 我们在这里使用 ManualRestEvet 的waitOne方法.
54 // 使用主函数暂停. 等待一下 set
55 allDone.WaitOne();
56 }
57 }
原文地址:https://www.cnblogs.com/easyfrog/p/2394003.html