结合PLINQ和Async方法 [英] Combining PLINQ with Async method
问题描述
我试图像这样组合我的PLINQ语句:
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();
使用这样的异步方法:
private async void GetTransactionDetails(string _trID)
{
await Task.Run(() =>
{
});
}
这样我就可以在这里简单地添加一个await运算符:
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();
我该如何实现?
P.S.这样,我可以同时发出5-10个HTTP请求,同时确保最终用户在这样做时不会感到任何屏幕"冻结...
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...
推荐答案
您可以采取几种方法.
首先,更正确"的方法(这也是更多的工作).将GetTransactionDetails
设置为正确的async
方法(即,不使用Task.Run
):
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);
如果需要限制并发性,请使用SemaphoreSlim
.
If you need to limit concurrency, use a SemaphoreSlim
.
第二种方法比较浪费(就线程使用而言),但是鉴于我们已经看到了代码的哪些部分,第二种方法可能会更容易.第二种方法是使所有I/O保持同步,并以常规PLINQ方式进行:
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();
为避免阻塞UI线程,可以将其包装在单个Task.Run
中:
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());
这篇关于结合PLINQ和Async方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!