如何限制并发的 异步IO 请求数量?
生活随笔
收集整理的這篇文章主要介紹了
如何限制并发的 异步IO 请求数量?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
咨詢區
Grief Coder:
我的項目中有下面一段代碼:
//?let's?say?there?is?a?list?of?1000+?URLs string[]?urls?=?{?"http://google.com",?"http://yahoo.com",?...?};//?now?let's?send?HTTP?requests?to?each?of?these?URLs?in?parallel urls.AsParallel().ForAll(async?(url)?=>?{var?client?=?new?HttpClient();var?html?=?await?client.GetStringAsync(url); });這段代碼有一個問題,當我開啟了 1000+ 的并發請求,是否有一種簡便的方式限制這些 異步http請求 并發量,比如說實現同一時刻不會超過 20 個下載,請問我該如何去實現?
回答區
Jay Shah:
可以使用 SemaphoreSlim,它可以非常完美的搞定,下面是我實現的擴展方法。
public?static?async?Task?ForEachAsyncConcurrent<T>(this?IEnumerable<T>?enumerable,Func<T,?Task>?action,int??maxActionsToRunInParallel?=?null){if?(maxActionsToRunInParallel.HasValue){using?(var?semaphoreSlim?=?new?SemaphoreSlim(maxActionsToRunInParallel.Value,?maxActionsToRunInParallel.Value)){var?tasksWithThrottler?=?new?List<Task>();foreach?(var?item?in?enumerable){//?Increment?the?number?of?currently?running?tasks?and?wait?if?they?are?more?than?limit.await?semaphoreSlim.WaitAsync();tasksWithThrottler.Add(Task.Run(async?()?=>{await?action(item).ContinueWith(res?=>{//?action?is?completed,?so?decrement?the?number?of?currently?running?taskssemaphoreSlim.Release();});}));}//?Wait?for?all?of?the?provided?tasks?to?complete.await?Task.WhenAll(tasksWithThrottler.ToArray());}}else{await?Task.WhenAll(enumerable.Select(item?=>?action(item)));}}然后像下面這樣使用。
await?enumerable.ForEachAsyncConcurrent(async?item?=>{await?SomeAsyncMethod(item);},5);Serge Semenov:
其實直接用 semaphore 稍不注意就會遇到很多的坑,而且排查起來還特別棘手,我建議你使用 AsyncEnumerator NuGet Package ,參考地址:https://www.nuget.org/packages/AsyncEnumerator/1.1.0 ?,這樣也不需要再造什么輪子了,參考如下代碼:
using?System.Linq; using?System.Buffers; using?Dasync.Collections;//?let's?say?there?is?a?list?of?1000+?URLs string[]?urls?=?{?"http://google.com",?"http://yahoo.com"};//?now?let's?send?HTTP?requests?to?each?of?these?URLs?in?parallel await?urls.ParallelForEachAsync(async?(url)?=>?{var?client?=?new?HttpClient();var?html?=?await?client.GetStringAsync(url); },maxDegreeOfParallelism:?20);點評區
在異步上做并發限制要比同步復雜的多,不過也是有一些可選方式,比如本篇的這兩種,學習了。
總結
以上是生活随笔為你收集整理的如何限制并发的 异步IO 请求数量?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET 6新特性试用 | 文件范围的命
- 下一篇: WPF 实现温度计