Nesting await in Parallel.ForEach

后端 未结 9 1318
别跟我提以往
别跟我提以往 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:29

    Wrap the Parallel.Foreach into a Task.Run() and instead of the await keyword use [yourasyncmethod].Result

    (you need to do the Task.Run thing to not block the UI thread)

    Something like this:

    var yourForeachTask = Task.Run(() =>
            {
                Parallel.ForEach(ids, i =>
                {
                    ICustomerRepo repo = new CustomerRepo();
                    var cust = repo.GetCustomer(i).Result;
                    customers.Add(cust);
                });
            });
    await yourForeachTask;
    

提交回复
热议问题