Replace Task.WhenAll with PLinq

混江龙づ霸主 提交于 2020-01-25 06:39:08

问题


I'm having a method which calls a WCF service multiple times in parallel. To prevent an overload on the target system, I want to use PLinq's ability to limit the number of parallel executions. Now I wonder how I could rewrite my method in an efficient way.

Here's my current implementation:

private async Task RunFullImport(IProgress<float> progress) {
    var dataEntryCache = new ConcurrentHashSet<int>();
    using var client = new ESBClient(); // WCF

    // Progress counters helpers
    float totalSteps = 1f / companyGroup.Count();
    int currentStep = 0;

    //Iterate over all resources
    await Task.WhenAll(companyGroup.Select(async res => {
        getWorkOrderForResourceDataSetResponse worResp = await client.getWorkOrderForResourceDataSetAsync(
            new getWorkOrderForResourceDataSetRequest(
                "?",
                res.Company,
                res.ResourceNumber,
                res.ResourceType,
                res.CLSName,
                fromDate,
                toDate,
                "D"
            )
        );

        // Iterate over all work orders and add them to the list
        foreach (dsyWorkOrder02TtyWorkOrderResource workOrder in worResp.dsyWorkOrder02) {
            dataEntryCache.Add(workOrder.DataEntryNumber.Value);
        }

        // Update progress
        progress.Report(totalSteps * Interlocked.Increment(ref currentStep) * .1f);
    }));

    // Do some more stuff with the result
}

I already tried some approaches to use PLinq instead, but I don't quite come up with a proper solution. This is my current state.

var p = companyGroup.Select(res => client.getWorkOrderForResourceDataSetAsync(
    new getWorkOrderForResourceDataSetRequest(
        "?",
        res.Company,
        res.ResourceNumber,
        res.ResourceType,
        res.CLSName,
        fromDate,
        toDate,
        "D"
    )
).ContinueWith(worResp => {
    // Iterate over all work orders and add them to the list
    foreach (dsyWorkOrder02TtyWorkOrderResource workOrder in worResp.Result.dsyWorkOrder02) {
        dataEntryCache.Add(workOrder.DataEntryNumber.Value);
    }

    // Update progress
    progress.Report(totalSteps * Interlocked.Increment(ref currentStep) * .1f);
}));

await Task.WhenAll(p.AsParallel().ToArray());

This, quite obviously, doesn't work properly. Do you have any suggestions to make it work properly and efficient and to limit the maximum calls to the server so 8 in parallel?


回答1:


PLINQ only works with synchronous code. It has some nice built-in knobs for controlling the number of concurrent parallel operations.

To control the number of concurrent asynchronous operations, use SemaphoreSlim:

private async Task RunFullImport(IProgress<float> progress) {
  var dataEntryCache = new ConcurrentHashSet<int>();
  using var client = new ESBClient(); // WCF
  var limiter = new SemaphoreSlim(10); // or however many you want to limit to.

  // Progress counters helpers
  float totalSteps = 1f / companyGroup.Count();
  int currentStep = 0;

  //Iterate over all resources
  await Task.WhenAll(companyGroup.Select(async res => {
    await limiter.WaitAsync();
    try {    
      getWorkOrderForResourceDataSetResponse worResp = ...

      // Iterate over all work orders and add them to the list
      foreach (dsyWorkOrder02TtyWorkOrderResource workOrder in worResp.dsyWorkOrder02) {
        dataEntryCache.Add(workOrder.DataEntryNumber.Value);
      }

      // Update progress
      progress.Report(totalSteps * Interlocked.Increment(ref currentStep) * .1f);
    }
    finally {
      limiter.Release();
    }
  }));

  // Do some more stuff with the result
}

For more information, see recipe 12.5 in my book, which covers several different solutions for throttling.



来源:https://stackoverflow.com/questions/59843575/replace-task-whenall-with-plinq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!