1

刚接触 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);
        }
    }
}
4

1 回答 1

0

正如其他人所说,Execute 方法不久前被弃用,现在完全消失了,那个 MSDN 示例已经很老了。

该方法略微违背了 AsyncEnumerator 类的观点,因为进行调用的线程将运行迭代器,直到第一次产生,然后阻塞,直到迭代器完成处理。

因此,将其替换为以下内容可能更清楚:

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

这看起来有点像从 AsyncEnumerator 迭代器中进行常规 APM 调用,并使阻塞更加明确。

于 2012-05-29T23:30:54.027 回答