C#异步调用的例子

 

异步代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Text;
  7 using System.Threading;
  8 using System.Windows.Forms;
  9 
 10 namespace CW
 11 {
 12     public partial class AsyncDemo : Form
 13     {
 14         public AsyncDemo()
 15         {
 16             InitializeComponent();
 17         }
 18 
 19         private void Delgate_Load(object sender, EventArgs e)
 20         {
 21 
 22         }
 23 
 24         /// <summary>
 25         /// 实现委托的方法
 26          /// </summary>
 27         /// <param name="iCallTime"></param>
 28         /// <param name="iExecThread"></param>
 29         /// <returns></returns>
 30         string LongRunningMethod(int iCallTime, out int iExecThread)
 31         {
 32             Thread.Sleep(iCallTime);
 33             iExecThread = AppDomain.GetCurrentThreadId();
 34             return "MyCallTime was " + iCallTime.ToString();
 35         }
 36 
 37         delegate string MethodDelegate(int iCallTime, out int iExecThread);
 38 
 39         #region 示例 1: 同步调用方法#region 示例 1: 同步调用方法
 40         /**/
 41         /*
 42          *  同步调用方法
 43          * */
 44         /**/
 45         /// <summary>
 46         /// 示例 1: 同步调用方法
 47         /// </summary>
 48         public void DemoSyncCall()
 49         {
 50             string s;
 51             int iExecThread;
 52 
 53             // Create an instance of a delegate that wraps LongRunningMethod.
 54             MethodDelegate dlgt = new MethodDelegate(this.LongRunningMethod);
 55 
 56             // Call LongRunningMethod using the delegate.
 57             s = dlgt(3000out iExecThread);
 58 
 59             MessageBox.Show(string.Format ("The delegate call returned the string: {0}, and the thread ID {1}", s, iExecThread.ToString() ) );
 60 
 61         }
 62         #endregion
 63 
 64         #region 示例 2: 通过 EndInvoke() 调用模式异步调用方法
 65         /**/
 66         /*
 67          * 使用调用模式是要调用 BeginInvoke , 做某些处理主线程, 并调用 EndInvoke() 。 
 68          * 注意不 EndInvoke() 不返回直到异步调用已完成。 
 69          * 此调用模式是有用当要有调用线程正在执行异步调用, 同时工作。 
 70          * 有同时发生工作可改善许多应用程序的性能。 
 71          * 常见任务以异步运行以此方式是文件或网络操作。 
 72          * */
 73         /**/
 74         /// <summary>
 75         /// 示例 2: 通过 EndInvoke() 调用模式异步调用方法        
 76         /// </summary>
 77         public void DemoEndInvoke()
 78         {
 79             MethodDelegate dlgt = new MethodDelegate(this.LongRunningMethod);
 80             string s;
 81             int iExecThread;
 82 
 83             // Initiate the asynchronous call.
 84             IAsyncResult ar = dlgt.BeginInvoke(5000out iExecThread, nullnull);
 85 
 86             // Do some useful work here. This would be work you want to have
 87             // run at the same time as the asynchronous call.
 88 
 89             // Retrieve the results of the asynchronous call.
 90             s = dlgt.EndInvoke(out iExecThread, ar);
 91 
 92             MessageBox.Show(string.Format ("The delegate call returned the string: {0}, and the number {1}", s, iExecThread.ToString() ) );
 93         }
 94         #endregion
 95 
 96         #region 示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成
 97         /**/
 98         /*
 99          * 由 BeginInvoke() 返回 IAsyncResult 具有一个 AsyncWaitHandle 属性。 
100          * 该属性返回 WaitHandle 异步调用完成后, 通知是。 等待 WaitHandle 是常见线程同步技术。 
101          * 通过是 WaitHandle WaitOne() 方法调用线程等待 WaitHandle 上。 
102          * 直到是通知 WaitHandle WaitOne() 块。 当 WaitOne() 返回, 您在调用 EndInvoke() 之前进行一些额外工作。 
103          * 对于执行文件或网络操作, 否则会阻塞调用主线程存为, 以前示例中此技术很有用。
104          * */
105         /**/
106         /// <summary>
107         /// 示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成
108         /// </summary>
109         public void DemoWaitHandle()
110         {
111             string s;
112             int iExecThread;
113 
114             MethodDelegate dlgt = new MethodDelegate(this.LongRunningMethod);
115 
116             // Initiate the asynchronous call.
117             IAsyncResult ar = dlgt.BeginInvoke(3000out iExecThread, nullnull);
118 
119             // Do some useful work here. This would be work you want to have
120             // run at the same time as the asynchronous call.
121 
122             // Wait for the WaitHandle to become signaled.
123             ar.AsyncWaitHandle.WaitOne();
124 
125             // Get the results of the asynchronous call.
126             s = dlgt.EndInvoke(out iExecThread, ar);
127 
128             MessageBox.Show(string.Format ("The delegate call returned the string: {0}, and the number {1}", s, iExecThread.ToString() ) );
129         }
130         #endregion
131 
132         #region 示例 4: 异步调用方法通过轮询调用模式
133         /**/
134         /*
135          * 由 BeginInvoke() 返回 IAsyncResult 对象有个 IsCompleted 属性异步调用完成后返回 True 。 
136          * 然后可调用 EndInvoke() 。 如果您应用程序不断工作对不做要长期函数调用已被此调用模式很有用。 
137          * MicrosoftWindows 应用程序是这样的示例。 
138          * 主线程的 Windows 应用程序可以继续以执行异步调用时处理用户输入。 
139          * 它可定期检查 IsCompleted 到调用是否完成。 它调用 EndInvoke 当 IsCompleted 返回 True 。 
140          * 直到它知道操作已完成因为 EndInvoke() 阻止直到异步操作为完整, 应用程序不调用它。 
141          * */
142         /**/
143         /// <summary>
144         /// 示例 4: 异步调用方法通过轮询调用模式
145         /// </summary>
146         public void DemoPolling()
147         {
148             MethodDelegate dlgt = new MethodDelegate(this.LongRunningMethod);
149             string s;
150             int iExecThread;
151 
152             // Initiate the asynchronous call.
153             IAsyncResult ar = dlgt.BeginInvoke(3000out iExecThread, nullnull);
154 
155             // Poll IAsyncResult.IsCompleted
156             while (ar.IsCompleted == false)
157             {
158                 Thread.Sleep(10);  // pretend to so some useful work
159             }
160             s = dlgt.EndInvoke(out iExecThread, ar);
161 
162             MessageBox.Show(string.Format ("The delegate call returned the string: {0}, and the number {1}", s, iExecThread.ToString() ) );
163         }
164         #endregion
165 
166         #region 示例 5: 异步方法完成后执行回调
167         /**/
168         /*
169          * 本节, 中示例提供对 BeginInvoke() 函数, 异步调用完成后系统执行回调委托。 
170          * 回调调用 EndInvoke() 并处理异步调用的结果。 
171          * 如果启动异步调用线程不需要处理结果是调用此调用模式很有用。 
172          * 异步调用完成后系统调用线程以外启动线程上调。 
173          * 若使用此调用模式, 作为第二到最后 - BeginInvoke() 函数的参数必须传递 AsyncCallback 类型的委托。 
174          * BeginInvoke() 还有最后参数键入 对象 到您可以将任何对象。 当它调用该对象可用于您回调函数。 
175          * 为此参数一个重要用途是以传递用于初始化调用该委托。 
176          * 回调函数然后使用与该委托 EndInvoke() 函数来完成调用。 此调用模式是所示。
177          * */
178         /**/
179         /// <summary>
180         /// 示例 5: 异步方法完成后执行回调
181         /// </summary>
182         public void DemoCallback()
183         {
184             MethodDelegate dlgt = new MethodDelegate(this.LongRunningMethod);
185             int iExecThread;
186 
187             // Create the callback delegate.
188             AsyncCallback cb = new AsyncCallback(MyAsyncCallback);
189 
190             // Initiate the Asynchronous call passing in the callback delegate
191             // and the delegate object used to initiate the call.
192             IAsyncResult ar = dlgt.BeginInvoke(5000out iExecThread, cb, dlgt);
193         }
194 
195         public void MyAsyncCallback(IAsyncResult ar)
196         {
197             string s;
198             int iExecThread;
199 
200             // Because you passed your original delegate in the asyncState parameter
201             // of the Begin call, you can get it back here to complete the call.
202             MethodDelegate dlgt = (MethodDelegate)ar.AsyncState;
203 
204             // Complete the call.
205             s = dlgt.EndInvoke(out iExecThread, ar);
206             MessageBox.Show(String.Format("The delegate call returned the string: {0}, and the number {1}", s, iExecThread.ToString()));
207 
208             //Console.WriteLine(string.Format ("The delegate call returned the string:   "{0}", and the number {1}", s, iExecThread.ToString() ) );
209         }
210         #endregion
211 
212         private void button1_Click(object sender, EventArgs e)
213         {
214             //DemoSyncCall() ;
215             //DemoEndInvoke();
216             //DemoWaitHandle();
217             //DemoPolling();
218             DemoCallback();
219         }
220     }
221 }
222 
223 

 

 

posted on 2010-11-17 13:04  jocxs  阅读(252)  评论(0编辑  收藏  举报

导航