Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throttle async functions in .Net?

I'm using async-await in .Net. How can I limit the number of concurrent asynchronous calls?

like image 284
Eyal Avatar asked Sep 15 '12 17:09

Eyal


People also ask

How does async improve performance?

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.

Do async functions run on another thread?

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.

Can we use async without Task?

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.


1 Answers

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();
}
like image 190
svick Avatar answered Oct 03 '22 13:10

svick