限制异步任务

时间:2014-03-18 22:28:12

标签: c# async-await semaphore throttling tpl-dataflow

我想运行一堆异步任务,并限制在任何给定时间可以完成的任务数量。

假设您有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

加成: 要解决BlockingCollectionTake()调用CompleteAdding()时出现异常的问题,我会使用TryTake重载超时。如果我没有在TryTake中使用超时,则会因BlockingCollection阻止TryTake而无法使用TakeAsync。有没有更好的办法?理想情况下,会有{{1}}方法。

3 个答案:

答案 0 :(得分:51)

根据建议,使用TPL Dataflow。

您可能正在寻找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完成,并检查缓冲区块。

答案 1 :(得分:42)

  

假设您有1000个网址,并且您只想打开50个请求   一个时间;但是只要一个请求完成,就会打开一个连接   到列表中的下一个URL。这样,总有50个   连接一次打开,直到URL列表用尽。

以下简单解决方案已在SO上多次浮出水面。它没有使用阻塞代码,也没有明确地创建线程,因此它可以很好地扩展:

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

答案 2 :(得分: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,以确保太多的Masters不会在链的开头进行缓冲,同时还留出足够的详细记录空间排队,以便一次处理150条记录。该块会向其目标输出object,因为它会在链接中进行过滤,具体取决于它是Detail还是Exception

batchAction ActionBlock收集所有批次的输出,并为每批次执行批量数据库更新,错误记录等。

将有几个BatchedJoinBlock,每个主人一个。由于每个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 });