使用Parallel.ForEach与/或异步/的await [英] using Parallel.ForEach with/or async/await
问题描述
我尝试验证我的形象的网址,看看他们是否是有效的。我有这么多的人,它需要几个小时才能完成这个任务。因此,我决定以异步方式做到这一点。我想知道,如果有如下当仁不让code的任何大的差异或优势。
I try to verify my image URLs to see whether or not they are valid. I have so many of them that it take hours to complete this task. Therefore, I decided to do it asynchronously. I would like to know if there are any big differences or advantage of doing my code as below.
我的主要职责是:
Async Function testUrl_async(ByVal myImageurl As String) As Task(Of Boolean)
myHttpResponse = Await myHttpClient.GetAsync(myImageurl)
If myHttpResponse.IsSuccessStatusCode Then
mySuccess = True
Else
mySuccess = False
End If
Return mySuccess
End Function
Function testUrl(ByVal myImageurl As String) As Boolean
myHttpResponse = myHttpClient.GetAsync(myImageurl)
If myHttpResponse.IsSuccessStatusCode Then
mySuccess = True
Else
mySuccess = False
End If
Return mySuccess
End Function
1)采用异步等待。
1) using async await.
For Each myImage In myImages
Dim result=await testUrl_async(myImageUrl).Result
'some code
Next
2)使用并行的foreach
2) using parallel foreach
Parallel.ForEach(myImages,
Sub(myImage)
testUrl(pictureComponent.websiteShop.hqpatronen, myImageUrl)
'some code
End Sub)
3)使用并行的foreach和asnyc /的await
3) using parallel foreach and asnyc/await
Parallel.ForEach(myImages,
Sub(myImage)
await testUrl_async(pictureComponent.websiteShop.hqpatronen, myImageUrl)
'some code
End Sub)
第三个可能是最好的解决办法,但它不会允许我这样称呼等待
/ 异步
中在的ForEach
。
如果我用的是第二个, testurl
函数具有异步HTTP调用,但不能与等待
, thereofore它与异常消息崩溃:
If I use the second one, the testurl
function has the async http call, but not with Await
, thereofore it crashes with the exception message:
[TaskCanceledException:一个任务被取消]
[TaskCanceledException: A task was canceled.]
在调用 myHttpClient.GetAsync
行。我猜测它抛出这个异常,因为的ForEach
已经结束,并要求取消HttpClient的,但并没有完成它的工作呢。我该如何处理这一点,如果这可能是最好的解决办法?
on the line that calls myHttpClient.GetAsync
. I am guessing that it throws this exception because ForEach
has ended and cancellation was requested but httpclient didn't finish its job yet. How can i handle this if this could be the best solution?
或者任何其他的解决方案,它使我的工作速度更快。
Alternatively any other solution which makes my job faster.
推荐答案
您肯定不希望使用 Parallel.ForEach
。 并行
是在多个内核US preading CPU绑定的算法,这将提供你任何好处(在你的情况下,你的算法是不是CPU绑定)。
You certainly don't want to use Parallel.ForEach
. Parallel
is for spreading CPU-bound algorithms over multiple cores, which would provide you no benefit (in your scenario, your algorithm is not CPU-bound).
你真正想要的是并发性,而不是并行。异步并行是可以做到用 Task.WhenAll
:
What you actually want is concurrency, not parallelism. Asynchronous concurrency can be done using Task.WhenAll
:
Dim tasks = myImages.Select(Function(x) testUrl_async(x))
Dim results = Await Task.WhenAll(tasks)
这篇关于使用Parallel.ForEach与/或异步/的await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!