-->

节流异步任务节流异步任务(Throttling asynchronous tasks)

2019-05-09 02:37发布

我想运行一堆异步任务,有多少任务可以在任何给定的时间等待完成的极限。

假设你有1000个网址,你只希望有50个请求在同一时间打开; 但只要一个请求完成后,你打开列表中的下一个URL连接。 这样一来,总有整整50个连接同时打开,直到URL列表被耗尽。

我也想利用线程如果可能的给定数。

我想出了一个扩展方法, ThrottleTasksAsync是我想要做什么。 是否有一个简单的解决方案已经在那里? 我会认为这是一个常见的场景。

用法:

class Program
{
    static void Main(string[] args)
    {
        Enumerable.Range(1, 10).ThrottleTasksAsync(5, 2, async i => { Console.WriteLine(i); return i; }).Wait();

        Console.WriteLine("Press a key to exit...");
        Console.ReadKey(true);
    }
}

下面是代码:

static class IEnumerableExtensions
{
    public static async Task<Result_T[]> ThrottleTasksAsync<Enumerable_T, Result_T>(this IEnumerable<Enumerable_T> enumerable, int maxConcurrentTasks, int maxDegreeOfParallelism, Func<Enumerable_T, Task<Result_T>> taskToRun)
    {
        var blockingQueue = new BlockingCollection<Enumerable_T>(new ConcurrentBag<Enumerable_T>());

        var semaphore = new SemaphoreSlim(maxConcurrentTasks);

        // Run the throttler on a separate thread.
        var t = Task.Run(() =>
        {
            foreach (var item in enumerable)
            {
                // Wait for the semaphore
                semaphore.Wait();
                blockingQueue.Add(item);
            }

            blockingQueue.CompleteAdding();
        });

        var taskList = new List<Task<Result_T>>();

        Parallel.ForEach(IterateUntilTrue(() => blockingQueue.IsCompleted), new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism },
        _ =>
        {
            Enumerable_T item;

            if (blockingQueue.TryTake(out item, 100))
            {
                taskList.Add(
                    // Run the task
                    taskToRun(item)
                    .ContinueWith(tsk =>
                        {
                            // For effect
                            Thread.Sleep(2000);

                            // Release the semaphore
                            semaphore.Release();

                            return tsk.Result;
                        }
                    )
                );
            }
        });

        // Await all the tasks.
        return await Task.WhenAll(taskList);
    }

    static IEnumerable<bool> IterateUntilTrue(Func<bool> condition)
    {
        while (!condition()) yield return true;
    }
}

该方法利用BlockingCollectionSemaphoreSlim ,使其工作。 该调节器是在一个线程中运行,并且所有的异步任务的其他线程上运行。 为了实现并行,我加则传递到一个maxDegreeOfParallelism参数Parallel.ForEach循环重新定意为while循环。

旧版本是:

foreach (var master = ...)
{
    var details = ...;
    Parallel.ForEach(details, detail => {
        // Process each detail record here
    }, new ParallelOptions { MaxDegreeOfParallelism = 15 });
    // Perform the final batch updates here
}

但是,线程池被耗尽快,你不能这样做async / await

奖励:为了避免在这个问题BlockingCollection其中一个例外是抛出Take()CompleteAdding()被调用时,我使用的是TryTake超载与超时。 如果我不使用超时TryTake ,它会破坏使用的目的BlockingCollection因为TryTake不会阻止。 有没有更好的办法? 理想的情况下,会有一个TakeAsync方法。

Answer 1:

至于建议,使用TPL数据流。

一个TransformBlock<TInput, TOutput>可能是你在找什么。

你定义一个MaxDegreeOfParallelism并行限制多少字符串可以转化(即多少网址可以下载)。 然后,您发布网址来将挡,而当你做你告诉块添加完项目和您取的响应。

var downloader = new TransformBlock<string, HttpResponse>(
        url => Download(url),
        new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 50 }
    );

var buffer = new BufferBlock<HttpResponse>();
downloader.LinkTo(buffer);

foreach(var url in urls)
    downloader.Post(url);
    //or await downloader.SendAsync(url);

downloader.Complete();
await downloader.Completion;

IList<HttpResponse> responses;
if (buffer.TryReceiveAll(out responses))
{
    //process responses
}

注: TransformBlock缓冲区它的两个输入和输出。 那么,为什么我们需要它链接到一个BufferBlock

因为TransformBlock将无法完成,直到所有( HttpResponse )已经被消耗掉,并await downloader.Completion会挂起。 相反,我们让downloader前所有输出到一个专用的缓冲块-然后我们等待downloader完成,并检查缓冲块。



Answer 2:

假设你有1000个网址,你只希望有50个请求在同一时间打开; 但只要一个请求完成后,你打开列表中的下一个URL连接。 这样一来,总有整整50个连接同时打开,直到URL列表被耗尽。

下面简单的解决方案已经在所以这里浮出水面多次。 它不使用阻塞代码没有明确创建线程,所以它做的非常好:

const int MAX_DOWNLOADS = 50;

static async Task DownloadAsync(string[] urls)
{
    using (var semaphore = new SemaphoreSlim(MAX_DOWNLOADS))
    using (var httpClient = new HttpClient())
    {
        var tasks = urls.Select(async url => 
        {
            await semaphore.WaitAsync();
            try
            {
                var data = await httpClient.GetStringAsync(url);
                Console.WriteLine(data);
            }
            finally
            {
                semaphore.Release();
            }
        });

        await Task.WhenAll(tasks);
    }
}

问题是,下载的数据的处理 ,应在不同的管道进行,具有不同级并行的,尤其是如果它是一个CPU密集型的处理。

例如,你可能想拥有4个线程并行执行数据处理(CPU内核的数量),并且最多可为更多的数据50个未决请求(这完全不使用线程)。 AFAICT,这不是目前你的代码是做什么的。

这就是TPL数据流或Rx可以派上用场的首选解决方案。 但它肯定是可以实现这样的事情用普通TPL。 注意,唯一阻止代码在这里是一个做内部的实际数据处理Task.Run

const int MAX_DOWNLOADS = 50;
const int MAX_PROCESSORS = 4;

// process data
class Processing
{
    SemaphoreSlim _semaphore = new SemaphoreSlim(MAX_PROCESSORS);
    HashSet<Task> _pending = new HashSet<Task>();
    object _lock = new Object();

    async Task ProcessAsync(string data)
    {
        await _semaphore.WaitAsync();
        try
        {
            await Task.Run(() =>
            {
                // simuate work
                Thread.Sleep(1000);
                Console.WriteLine(data);
            });
        }
        finally
        {
            _semaphore.Release();
        }
    }

    public async void QueueItemAsync(string data)
    {
        var task = ProcessAsync(data);
        lock (_lock)
            _pending.Add(task);
        try
        {
            await task;
        }
        catch
        {
            if (!task.IsCanceled && !task.IsFaulted)
                throw; // not the task's exception, rethrow
            // don't remove faulted/cancelled tasks from the list
            return;
        }
        // remove successfully completed tasks from the list 
        lock (_lock)
            _pending.Remove(task);
    }

    public async Task WaitForCompleteAsync()
    {
        Task[] tasks;
        lock (_lock)
            tasks = _pending.ToArray();
        await Task.WhenAll(tasks);
    }
}

// download data
static async Task DownloadAsync(string[] urls)
{
    var processing = new Processing();

    using (var semaphore = new SemaphoreSlim(MAX_DOWNLOADS))
    using (var httpClient = new HttpClient())
    {
        var tasks = urls.Select(async (url) =>
        {
            await semaphore.WaitAsync();
            try
            {
                var data = await httpClient.GetStringAsync(url);
                // put the result on the processing pipeline
                processing.QueueItemAsync(data);
            }
            finally
            {
                semaphore.Release();
            }
        });

        await Task.WhenAll(tasks.ToArray());
        await processing.WaitForCompleteAsync();
    }
}


Answer 3:

按照要求,这里是我结束了去的代码。

这项工作是建立在一个主从配置,并且每个主被处理为一个批次。 每个工作单元被以这种方式排队:

var success = true;

// Start processing all the master records.
Master master;
while (null != (master = await StoredProcedures.ClaimRecordsAsync(...)))
{
    await masterBuffer.SendAsync(master);
}

// Finished sending master records
masterBuffer.Complete();

// Now, wait for all the batches to complete.
await batchAction.Completion;

return success;

大师是缓冲一次一个保存为其他外部流程的工作。 每个主站的细节分派通过工作masterTransform TransformManyBlock 。 一个BatchedJoinBlock还创建收集细节在一个批次。

实际工作是在做detailTransform TransformBlock的时间,异步,150。 BoundedCapacity设置为300,以确保太多的大师没有得到在链的开始缓冲,同时还留有一定空间足够详细记录排队,让150个记录在同一时间进行处理。 块输出一个object到它的目标,因为它在整个链路过滤取决于它是否是一个DetailException

所述batchAction ActionBlock收集来自所有批次的输出,并且执行散装数据库更新,错误日志等。对于每个批次。

会有几个BatchedJoinBlock S,为每个主。 由于每个ISourceBlock是依次输出,并且每个批次仅接受与一个主相关联的细节的记录数,批次将按顺序进行处理。 每个块只输出一个基团,并且是在完成解除链接。 只有最后一批块传播其完成最终ActionBlock

数据流网络:

// The dataflow network
BufferBlock<Master> masterBuffer = null;
TransformManyBlock<Master, Detail> masterTransform = null;
TransformBlock<Detail, object> detailTransform = null;
ActionBlock<Tuple<IList<object>, IList<object>>> batchAction = null;

// Buffer master records to enable efficient throttling.
masterBuffer = new BufferBlock<Master>(new DataflowBlockOptions { BoundedCapacity = 1 });

// Sequentially transform master records into a stream of detail records.
masterTransform = new TransformManyBlock<Master, Detail>(async masterRecord =>
{
    var records = await StoredProcedures.GetObjectsAsync(masterRecord);

    // Filter the master records based on some criteria here
    var filteredRecords = records;

    // Only propagate completion to the last batch
    var propagateCompletion = masterBuffer.Completion.IsCompleted && masterTransform.InputCount == 0;

    // Create a batch join block to encapsulate the results of the master record.
    var batchjoinblock = new BatchedJoinBlock<object, object>(records.Count(), new GroupingDataflowBlockOptions { MaxNumberOfGroups = 1 });

    // Add the batch block to the detail transform pipeline's link queue, and link the batch block to the the batch action block.
    var detailLink1 = detailTransform.LinkTo(batchjoinblock.Target1, detailResult => detailResult is Detail);
    var detailLink2 = detailTransform.LinkTo(batchjoinblock.Target2, detailResult => detailResult is Exception);
    var batchLink = batchjoinblock.LinkTo(batchAction, new DataflowLinkOptions { PropagateCompletion = propagateCompletion });

    // Unlink batchjoinblock upon completion.
    // (the returned task does not need to be awaited, despite the warning.)
    batchjoinblock.Completion.ContinueWith(task =>
    {
        detailLink1.Dispose();
        detailLink2.Dispose();
        batchLink.Dispose();
    });

    return filteredRecords;
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });

// Process each detail record asynchronously, 150 at a time.
detailTransform = new TransformBlock<Detail, object>(async detail => {
    try
    {
        // Perform the action for each detail here asynchronously
        await DoSomethingAsync();

        return detail;
    }
    catch (Exception e)
    {
        success = false;
        return e;
    }

}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 150, BoundedCapacity = 300 });

// Perform the proper action for each batch
batchAction = new ActionBlock<Tuple<IList<object>, IList<object>>>(async batch =>
{
    var details = batch.Item1.Cast<Detail>();
    var errors = batch.Item2.Cast<Exception>();

    // Do something with the batch here
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 });

masterBuffer.LinkTo(masterTransform, new DataflowLinkOptions { PropagateCompletion = true });
masterTransform.LinkTo(detailTransform, new DataflowLinkOptions { PropagateCompletion = true });


文章来源: Throttling asynchronous tasks