與異步lambda函數的並行處理
結合併行處理和異步lambda函數需要仔細考慮。 本文解決了在
中使用方法的挑戰,並提供有效的解決方案。 async
Parallel.ForEach
>
的問題
啟動背景線程,這些線程本質上不等待任務完成。 這會在Lambda表達式內使用時會產生問題。以下示例說明了此問題:Parallel.ForEach
await
<code class="language-csharp">var bag = new ConcurrentBag<object>(); Parallel.ForEach(myCollection, async item => { // some pre-processing var response = await GetData(item); bag.Add(response); // some post-processing }); var count = bag.Count; // count will be 0</code>作為解決方法,否定了
的好處,並且需要明確的例外處理:count
Wait()
使用task.whenall await
<code class="language-csharp">var bag = new ConcurrentBag<object>(); Parallel.ForEach(myCollection, item => { // some pre-processing var responseTask = GetData(item); responseTask.Wait(); var response = responseTask.Result; bag.Add(response); // some post-processing }); var count = bag.Count;</code>
一個更有效的解決方案涉及利用來管理異步操作:
Task.WhenAll
這種方法允許各項處理每個項目,並確保所有任務在繼續執行之前完成。
<code class="language-csharp">var bag = new ConcurrentBag<object>(); var tasks = myCollection.Select(async item => { // some pre-processing var response = await GetData(item); bag.Add(response); // some post-processing }); await Task.WhenAll(tasks); var count = bag.Count; // count will be correct</code>高級解決方案:foreachAsync
Task.WhenAll
>
以上是我如何與Parallel.Foreach合適使用異步Lambda函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!