Nesting await in Parallel.ForEach

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

    This should be pretty efficient, and easier than getting the whole TPL Dataflow working:

    var customers = await ids.SelectAsync(async i =>
    {
        ICustomerRepo repo = new CustomerRepo();
        return await repo.GetCustomer(i);
    });
    
    ...
    
    public static async Task> SelectAsync(this IEnumerable source, Func> selector, int maxDegreesOfParallelism = 4)
    {
        var results = new List();
    
        var activeTasks = new HashSet>();
        foreach (var item in source)
        {
            activeTasks.Add(selector(item));
            if (activeTasks.Count >= maxDegreesOfParallelism)
            {
                var completed = await Task.WhenAny(activeTasks);
                activeTasks.Remove(completed);
                results.Add(completed.Result);
            }
        }
    
        results.AddRange(await Task.WhenAll(activeTasks));
        return results;
    }
    

提交回复
热议问题