publicclass AsyncDemo ...{ // Use in asynchronous methods privatedelegatestring runDelegate(); privatestring m_Name; private runDelegate m_Delegate; public AsyncDemo(string name) ...{ m_Name = name; m_Delegate =new runDelegate(Run); } /**//**//**//// /// Synchronous method /// /// publicstring Run() ...{ return"My name is "+ m_Name; } /**//**//**//// /// Asynchronous begin method /// /// /// /// public IAsyncResult BeginRun(AsyncCallback callBack, Object stateObject) ...{ try ...{ return m_Delegate.BeginInvoke(callBack, stateObject); } catch(Exception e) ...{ // Hide inside method invoking stack throw e; } } /**//**//**//// /// Asynchronous end method /// /// /// publicstring EndRun(IAsyncResult ar) ...{ if (ar ==null) thrownew NullReferenceException("Arggument ar can't be null"); try ...{ return m_Delegate.EndInvoke(ar); } catch (Exception e) ...{ // Hide inside method invoking stack throw e; } } }
首先是 Begin 之后直接调用 End 方法,当然中间也可以做其他的操作
class AsyncTest ...{ staticvoid Main(string[] args) ...{ AsyncDemo demo =new AsyncDemo("jiangnii"); // Execute begin method IAsyncResult ar = demo.BeginRun(null, null); // You can do other things here // Use end method to block thread until the operation is complete string demoName = demo.EndRun(ar); Console.WriteLine(demoName); } } 也可以用 IAsyncResult 的 AsyncWaitHandle 属性,我在这里设置为1秒超时 class AsyncTest ...{ staticvoid Main(string[] args) ...{ AsyncDemo demo =new AsyncDemo("jiangnii"); // Execute begin method IAsyncResult ar = demo.BeginRun(null, null); // You can do other things here // Use AsyncWaitHandle.WaitOne method to block thread for 1 second at most ar.AsyncWaitHandle.WaitOne(1000, false); if (ar.IsCompleted) ...{ // Still need use end method to get result, but this time it will return immediately string demoName = demo.EndRun(ar); Console.WriteLine(demoName); } else ...{ Console.WriteLine("Sorry, can't get demoName, the time is over"); } } } //不中断的轮循,每次循环输出一个 "." class AsyncTest ...{ staticvoid Main(string[] args) ...{ AsyncDemo demo =new AsyncDemo("jiangnii"); // Execute begin method IAsyncResult ar = demo.BeginRun(null, null); Console.Write("Waiting.."); while (!ar.IsCompleted) ...{ Console.Write("."); // You can do other things here } Console.WriteLine(); // Still need use end method to get result, but this time it will return immediately string demoName = demo.EndRun(ar); Console.WriteLine(demoName); } }