2012-05-22 83 views
0

只需掌握AsyncEnumerator庫並不確定缺少哪一部分。 我試圖去運行由庫的作者提供an example自己,但不知道什麼是該行「執行」:AsyncEnumerator使用示例

ae.Execute(ProcessAllAndEachOps(ae, urls)); 

方法參考。 有人可以給我一些線索嗎?

更新: 我設法通過對以下代碼中已包含的一些更改進行運行。值得注意的是,Peter注意到AsyncEnumerator對象的Execute()方法已經過時,應該用一些輔助函數替換掉。

using System; 
using System.Collections.Generic; 
using System.Net; 
using Wintellect.Threading.AsyncProgModel; 


public static class AsyncEnumeratorPatterns { 

    private static void Execute(AsyncEnumerator ae, IEnumerator<Int32> enumerator){ 
        ae.EndExecute(ae.BeginExecute(enumerator, null)); 
    } 

     public static void Main() { 
     String[] urls = new String[] { 
      "http://Wintellect.com/", 
      "http://1.1.1.1/", // Demonstrates error recovery 
      "http://www.Devscovery.com/" 
     }; 

     // Demonstrate process 
     AsyncEnumerator ae = new AsyncEnumerator(); 
     Execute(ae, ProcessAllAndEachOps(ae, urls)); 
     } 

     private static IEnumerator<Int32> ProcessAllAndEachOps(
      AsyncEnumerator ae, String[] urls) { 
     Int32 numOps = urls.Length; 

     // Issue all the asynchronous operation(s) so they run concurrently 
     for (Int32 n = 0; n < numOps; n++) { 
      WebRequest wr = WebRequest.Create(urls[n]); 
      wr.BeginGetResponse(ae.End(), wr); 
     } 

     // Have AsyncEnumerator wait until ALL operations complete 
     yield return numOps; 

     Console.WriteLine("All the operations completed:"); 
     for (Int32 n = 0; n < numOps; n++) { 
      ProcessCompletedWebRequest(ae.DequeueAsyncResult()); 
     } 

     Console.WriteLine(); // *** Blank line between demos *** 

     // Issue all the asynchronous operation(s) so they run concurrently 
     for (Int32 n = 0; n < numOps; n++) { 
      WebRequest wr = WebRequest.Create(urls[n]); 
      wr.BeginGetResponse(ae.End(), wr); 
     } 

     for (Int32 n = 0; n < numOps; n++) { 
      // Have AsyncEnumerator wait until EACH operation completes 
      yield return 1; 

      Console.WriteLine("An operation completed:"); 
      ProcessCompletedWebRequest(ae.DequeueAsyncResult()); 
     } 
     } 

     private static void ProcessCompletedWebRequest(IAsyncResult ar) { 
     WebRequest wr = (WebRequest)ar.AsyncState; 
     try { 
      Console.Write(" Uri=" + wr.RequestUri + " "); 
      using (WebResponse response = wr.EndGetResponse(ar)) { 
      Console.WriteLine("ContentLength=" + response.ContentLength); 
      } 
     } 
     catch (WebException e) { 
      Console.WriteLine("WebException=" + e.Message); 
     } 
    } 
} 
+0

從給定的代碼片段看來,它似乎只是啓動asyncenumeration過程。 – daryal

+0

嗯,是的,它確實開始執行,但它在哪裏定義? – matcheek

+0

右鍵單擊它並選擇「轉到定義」。這應該給你提示方法的定義。 –

回答

0

正如其他人所說的,Execute方法在前一段時間被棄用,現在完全消失了,MSDN示例已經很老了。

該方法輕微擊敗了AsyncEnumerator類的點,因爲調用的線程將運行迭代器直到第一個yield,然後阻塞,直到迭代器完成處理。

所以它也許更清晰用來替換:

var asyncResult = ae.BeginExecute(ProcessAllAndEachOps(ae, urls), null); 
asyncResult.AsyncWaitHandle.WaitOne(); 
ae.EndExecute(asyncResult); 

這看起來有點更像製作規整APM從AsyncEnumerator迭代器中調用,使攔截更加明確。