Combining PLINQ with Async method

邮差的信 提交于 2020-01-04 06:27:13

问题


I'm trying to combine my PLINQ statement like this:

Enumerable.Range(0, _sortedList.Count()).AsParallel().WithDegreeOfParallelism(10)
          .Select(i =>  GetTransactionDetails(_sortedList[i].TransactionID))
          .ToList();

With an async method like this:

 private async void GetTransactionDetails(string _trID)
 {
      await Task.Run(() =>
      {
      });
 }

So that I can simply add an await operator in here:

 Enumerable.Range(0, _sortedList.Count()).AsParallel().WithDegreeOfParallelism(10)
           .Select(i => await GetTransactionDetails(_sortedList[i].TransactionID))
           .ToList();

How can I achieve this ?

P.S. This way I could make 5-10 HTTP requests simultaneously while ensuring that the end user doesn't feels any "screen" freezing while doing so...


回答1:


There's a couple approaches you can take.

First, the "more correct" approach (which is also more work). Make GetTransactionDetails into a proper async method (i.e., does not use Task.Run):

private async Task GetTransactionDetailsAsync(string _trID);

Then you can call that method concurrently:

var tasks = _sortedList.Select(x => GetTransactionDetailsAsync(x.TransactionID));
await Task.WhenAll(tasks);

If you need to limit concurrency, use a SemaphoreSlim.

The second approach is more wasteful (in terms of thread usage), but is probably easier given what parts of your code we've seen. The second approach is to leave the I/O all synchronous and just do it in a regular PLINQ fashion:

private void GetTransactionDetails(string _trID);

_sortedList.AsParallel().WithDegreeOfParallelism(10).Select(x => GetTransactionDetails(x.TransactionID)).ToList();

To avoid blocking the UI thread, you can wrap this in a single Task.Run:

await Task.Run(() => _sortedList.AsParallel().WithDegreeOfParallelism(10).Select(x => GetTransactionDetails(x.TransactionID)).ToList());


来源:https://stackoverflow.com/questions/41126283/combining-plinq-with-async-method

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