Parallel.ForEach的奇怪行为

时间:2014-06-29 21:08:20

标签: c# .net async-await windows-8.1 parallel.foreach

我有以下代码:

Parallel.ForEach(xRoot.Elements("key"), xKey =>
{
    int id = int.Parse(xKey.Attribute("id").Value);
    string code = xKey.Attribute("code").Value;

    AccountStatus accountStatus = SomeClient.GetAccountStatusAsync(id, code).Result;
);

xRoot.Elements(" key")的计数是3,但ForEach只迭代2次。为什么呢?

2 个答案:

答案 0 :(得分:4)

混合Parallel.ForEachasync/await isn't a good idea。您不需要在 parallel 中执行异步方法,您需要它们同时执行 。您当前的代码在I / O操作上使用线程池线程阻止,忽略了异步api的优势。

试试这个:

var codeIds = xRoot.Elements("key").Select(xKey => new { Id = int.Parse(xKey.Attribute("id").Value, Code = xKey.Attribute("code").Value  });

var codeTasks = codeIds.Select(x => SomeClient.GetAccountStatusAsync(x.Id, x.Code));

await Task.WhenAll(codeTasks);

答案 1 :(得分:-1)

尝试:

Parallel.ForEach(xRoot.Elements("key"), async xKey =>
{
   int id = int.Parse(xKey.Attribute("id").Value);
   string code = xKey.Attribute("code").Value;

   AccountStatus accountStatus = await SomeClient.GetAccountStatusAsync(id, code);
);

或者:

Parallel.ForEach(xRoot.Elements("key"), xKey =>
{
   try
   {
      int id = int.Parse(xKey.Attribute("id").Value); // maybe null reference here?
      string code = xKey.Attribute("code").Value; // or here?

      AccountStatus accountStatus = SomeClient.GetAccountStatusAsync(id, code).Result; // or even here?
   }
   catch (Exception ex)
   {
      throw; // add here a breakpoint and check what's up by checking 'ex' object
   }
);