处理异步调用超时
使用ThreadPool.RegisterWaitForSingleObject方法和回调处理异步调用超时。
class Program { delegate void TestHandler(); static void Main() { // 创建委托 TestHandler t = new TestHandler( delegate { Thread.Sleep(10000); Console.WriteLine("Test..."); }); // 执行委托异步调用,并指定回调方法。 IAsyncResult ar = t.BeginInvoke( delegate(IAsyncResult r) { Console.WriteLine("CallBack..."); t.EndInvoke(r); }, null); // 使用线程池处理异步超时。 ThreadPool.RegisterWaitForSingleObject(ar.AsyncWaitHandle, delegate(object state, bool timeout) { // 该方法在指定时间到达后无论是否超时都会执行,因此需要判断timeout参数。 if (timeout) Console.WriteLine("Timeout..."); }, t, 5000, true); Console.WriteLine("Press any key to exit..."); Console.ReadKey(true); } }