这段代码是否同步,因为我想要它?

时间:2013-04-09 15:07:20

标签: c# task-parallel-library .net-4.5 async-await c#-5.0

我有这段代码

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次调用之前打印其结果。目前似乎没有发生这种情况。我做错了什么?

1 个答案:

答案 0 :(得分: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();
}