.NET排队任务(使用async / await)

时间:2016-12-06 21:20:38

标签: .net async-await task-parallel-library tpl-dataflow

我有大量需要执行的任务(~1000)。我使用的是4核处理器,因此我希望一次处理4个任务。

为了给你一个起点,这里有一些示例代码。

class Program
{
    public class LongOperation
    {
        private static readonly Random RandomNumberGenerator = new Random(0);
        const int UpdateFrequencyMilliseconds = 100;

        public int CurrentProgress { get; set; }

        public int TargetProcess { get; set; }

        public LongOperation()
        {
            TargetProcess = RandomNumberGenerator.Next(
                (int)TimeSpan.FromSeconds(5).TotalMilliseconds / UpdateFrequencyMilliseconds, 
                (int)TimeSpan.FromSeconds(10).TotalMilliseconds / UpdateFrequencyMilliseconds);
        }

        public async Task Execute()
        {
            while (!IsCompleted)
            {
                await Task.Delay(UpdateFrequencyMilliseconds);
                CurrentProgress++;
            }
        }

        public bool IsCompleted => CurrentProgress >= TargetProcess;
    }

    static void Main(string[] args)
    {
        Task.Factory.StartNew(async () =>
        {
            var operations = new List<LongOperation>();

            for(var x = 1; x <= 10; x++)
                operations.Add(new LongOperation());

            await ProcessOperations(4, operations);
        }).Wait();
    }

    public static async Task ProcessOperations(int maxSimultaneous, List<LongOperation> operations)
    {
        await Task.WhenAll(operations.Select(x => x.Execute()));
        // TODO: Process up to 4 operations at a time, until every operation is completed.
    }
}

我想对我将使用哪些类进行一些输入,以及我如何构建ProcessOperations一次最多处理4个操作,直到所有操作都完成为止,单一等待Task

我想以某种方式使用SemaphoreSlim对象,因为它似乎是为了限制资源/进程。

1 个答案:

答案 0 :(得分:3)

正如已经提出的那样,你需要使用一个方便的TPL Dataflow library,它有两个块,用于在处理之前存储消息,以及对它们的实际操作:

// storage
var operations = new BufferBlock<LongOperation>();
// no more than 4 actions at the time
var actions = new ActionBlock<LongOperation>(x => x.Execute(),
    new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 });

// consume new operations automatically
operations.LinkTo(actions);
for(var x = 1; x <= 10; ++x)
{
    // blocking sending
    operations.Post(new LongOperation());
    // awaitable send for async operations
    // await operations.SendAsync(new LongOperation());
}

此外,您可以通过设置缓冲区的BoundedCapacity选项来降低某些限制限制,例如当时不超过30个操作。