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

Pau*_*opf 5 .net task-parallel-library async-await 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要一些关于我将使用哪些类的输入,以及我如何ProcessOperations在一个 await-able 中构建一次最多处理 4 个操作,直到所有操作完成Task

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

VMA*_*Atm 2

正如已经建议的,您需要使用一个方便的TPL 数据流库,它有两个块,用于在处理之前存储消息,并对它们采取实际操作:

// 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());
}
Run Code Online (Sandbox Code Playgroud)

BoundedCapacity此外,您还可以通过设置缓冲区选项来引入一些限制,例如一次不超过 30 次操作。