I'm using async-await in .Net. How can I limit the number of concurrent asynchronous calls?
Asynchronous programming can in some cases help with performance by parallelizing a task. But, that is not its main benefit in day to day development. Instead, the main benefit comes from making our code more scalable. The scalability feature of a system relates to how it handles a growing amount of work.
The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread.
If the work you have is I/O-bound, use async and await without Task. Run . You should not use the Task Parallel Library. If the work you have is CPU-bound and you care about responsiveness, use async and await , but spawn off the work on another thread with Task.
One relatively simple way is to (ab)use TPL Dataflow. Something like:
public IEnumerable<TOutput> AsyncThrottle<TInput, TOutput>(
IEnumerable<TInput> inputs, Func<TInput, Task<TOutput>> asyncFunction,
int maxDegreeOfParallelism)
{
var outputs = new ConcurrentQueue<TOutput>();
var block = new ActionBlock<TInput>(
async x => outputs.Enqueue(await asyncFunction(x)),
new ExecutionDataflowBlockOptions
{ MaxDgreeOfParallelism = maxDegreeOfParallelism });
foreach (var input in inputs)
block.Send(input);
block.Complete();
block.Completion.Wait();
return outputs.ToArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With