1

我有这个代码

public async Task<IEnumerable<WebResult>> SearchAsynch(string query)
{
  if (query == null)
  {
     throw new ArgumentNullException("query cannot be null");
  }

  DataServiceQuery<WebResult> webQuery =
 _bingContainer.Web(query, null, null, null, null, null, null, null);

  return await Task.Factory.FromAsync
                 (webQuery.BeginExecute(null, null)
                 , asyncResult => webQuery.EndExecute(asyncResult)
                 );
}

我这样称呼它

public static void Main()
{
   Search().Wait();
}

private static async Task Search()
{
  IWebSearcher webSearcher = new WebSearcher();
  for (var i = 0; i < 100; i++)
  {
      IEnumerable<WebResult> task = await webSearcher.SearchAsynch(i.ToString());

      var enumerator = task.GetEnumerator();
      enumerator.MoveNext();
      Console.WriteLine(enumerator.Current.Title);
   }
}

我遇到的问题是这个。我希望这 100 个调用中SearchAsynch的每一个都完全相互独立,以便第 10 个调用可以在第 9 个调用之前返回并打印其结果。目前似乎没有发生这种情况。有什么我做错了吗?

4

1 回答 1

2

在任务完成时进行处理的最简单方法是定义一个单独的方法来进行处理,如下所示:

public static async Task SearchAndPrintAsync(IWebSearcher webSearcher, string query)
{
  var result = await webSearcher.SearchAsync(query);
  using (var enumerator = result.GetEnumerator())
  {
    if (enumerator.MoveNext())
      Console.WriteLine(enumerator.Current.Title);
    else
      Console.WriteLine("<none>");
  }
}

然后你可以async像这样进行并发操作:

private static async Task MainAsync()
{
    IWebSearcher webSearcher = new WebSearcher();

    // Start all SearchAndPrint operations concurrently.
    Task[] tasks = Enumerable.Range(0, 100)
        .Select(i => SearchAndPrintAsync(webSearcher, i))
        .ToArray();

    // Wait for them all to complete.
    await Task.WhenAll(tasks);

    Console.WriteLine("Done");
}

public static void Main()
{
    MainAsync().Wait();
}
于 2013-04-09T15:28:36.677 回答