利用异步委托实现异步编程
1
using System;2
using System.Threading; 3

4
namespace Examples.AdvancedProgramming.AsynchronousOperations5


{6
public class AsyncDemo 7

{8
// The method to be executed asynchronously.9
public string TestMethod(int callDuration, out int threadId) 10

{11
Console.WriteLine("Test method begins.");12
Thread.Sleep(callDuration);13
threadId = Thread.CurrentThread.GetHashCode();14
return String.Format("My call time was {0}.", callDuration.ToString());15
}16
}17
// The delegate must have the same signature as the method18
// it will call asynchronously.19
public delegate string AsyncMethodCaller(int callDuration, out int threadId);20
}1
using System;2
using System.Threading;3

4
namespace Examples.AdvancedProgramming.AsynchronousOperations5


{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
}

浙公网安备 33010602011771号