Nesting await in Parallel.ForEach

后端 未结 9 1333
别跟我提以往
别跟我提以往 2020-11-22 01:01

In a metro app, I need to execute a number of WCF calls. There are a significant number of calls to be made, so I need to do them in a parallel loop. The problem is that th

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 01:39

    svick's answer is (as usual) excellent.

    However, I find Dataflow to be more useful when you actually have large amounts of data to transfer. Or when you need an async-compatible queue.

    In your case, a simpler solution is to just use the async-style parallelism:

    var ids = new List() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
    
    var customerTasks = ids.Select(i =>
      {
        ICustomerRepo repo = new CustomerRepo();
        return repo.GetCustomer(i);
      });
    var customers = await Task.WhenAll(customerTasks);
    
    foreach (var customer in customers)
    {
      Console.WriteLine(customer.ID);
    }
    
    Console.ReadKey();
    

提交回复
热议问题