我用一个 AsyncDemo 类作为异步方法的提供者,后面的程序都会调用它。内部很简单,构造函数接收一个字符串作为 name ,Run 方法输出 "My name is " + name ,而异步方法直接用委托的 BeginInvoke 和 EndInvoke 方法实现
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); } /**////<summary> /// Synchronous method ///</summary> ///<returns></returns> publicstring Run() { return"My name is "+ m_Name; } /**////<summary> /// Asynchronous begin method ///</summary> ///<param name="callBack"></param> ///<param name="stateObject"></param> ///<returns></returns> public IAsyncResult BeginRun(AsyncCallback callBack, Object stateObject) { try { return m_Delegate.BeginInvoke(callBack, stateObject); } catch(Exception e) { // Hide inside method invoking stack throw e; } } /**////<summary> /// Asynchronous end method ///</summary> ///<param name="ar"></param> ///<returns></returns> 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); } }
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); } }
/**////<summary> /// DoWork event process method ///</summary> ///<param name="sender"></param> ///<param name="e"></param> privatevoid BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { long length; using (StreamReader sr =new StreamReader(m_FilePath)) { // Get file length length = sr.ReadToEnd().Length; } using (StreamReader sr =new StreamReader(m_FilePath)) { long onePercentOfLength = length /100; long currentPosition =0; int i =0; while (!sr.EndOfStream) { sr.Read(); currentPosition ++; // Produce ProcessChanged event in each percent reading while (currentPosition > onePercentOfLength * i) { ((BackgroundWorker)sender).ReportProgress(i++); } } // e.Result will be used in RunWorkerCompleted event process method e.Result = currentPosition; } }