您的位置:首页 > 编程语言

利用异步委托实现异步编程

2006-12-25 11:44 609 查看
using System;
2using System.Threading;
3
4namespace Examples.AdvancedProgramming.AsynchronousOperations
5using System;
2using System.Threading;
3
4namespace Examples.AdvancedProgramming.AsynchronousOperations
5{
6 public class AsyncMain
7 {
8 static int threadId;
9
10 public static void Main()
11 {
12 // The asynchronous method puts the thread id here.
13
14 // Create an instance of the test class.
15 AsyncDemo ad = new AsyncDemo();
16
17 // Create the delegate.
18 AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
19
20// // Initiate the asychronous call.
21// IAsyncResult result = caller.BeginInvoke(3000,out threadId, null, null);
22
23 IAsyncResult result = caller.BeginInvoke(3000,
24 out threadId,
25 new AsyncCallback(CallbackMethod),
26 caller );
27
28 Console.WriteLine("Press Enter to close application.");
29 Console.ReadLine();
30
31
32// Thread.Sleep(0);
33// Console.WriteLine("Main thread {0} does some work.",
34// Thread.CurrentThread.GetHashCode());
35//
36// // Wait for the WaitHandle to become signaled.
37// result.AsyncWaitHandle.WaitOne();
38//
39// // Poll while simulating work.
40// while(result.IsCompleted == false)
41// {
42// Thread.Sleep(10);
43// }
44//
45// // Call EndInvoke to wait for the asynchronous call to complete,
46// // and to retrieve the results.
47// string returnValue = caller.EndInvoke(out threadId, result);
48//
49// Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
50// threadId, returnValue);
51// Console.ReadLine();
52 }
53 static void CallbackMethod(IAsyncResult ar)
54 {
55 // Retrieve the delegate.
56 AsyncMethodCaller caller = (AsyncMethodCaller) ar.AsyncState;
57
58 // Call EndInvoke to retrieve the results.
59 string returnValue = caller.EndInvoke(out threadId, ar);
60
61 Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
62 threadId, returnValue);
63 }
64 }
65}
当主调用线程,调用异步方法后,可以阻塞自己,也可以处理一些操作。也可以自定义异步线程的回调方法。还在学习中。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: