我怎样才能油门净异步功能呢? [英] How can I throttle async functions in .Net?

查看:120
本文介绍了我怎样才能油门净异步功能呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是异步,等待在.NET。如何限制并发异步调用的次数?

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

推荐答案

一个比较简单的方法是(AB)使用TPL数据流。是这样的:

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();
}

这篇关于我怎样才能油门净异步功能呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆