Best way to limit the number of active Tasks running via the Parallel Task Library

前端 未结 6 1902
春和景丽
春和景丽 2020-12-02 16:54

Consider a queue holding a lot of jobs that need processing. Limitation of queue is can only get 1 job at a time and no way of knowing how many jobs there a

6条回答
  •  执念已碎
    2020-12-02 17:52

    Microsoft has a very cool library called DataFlow which does exactly what you want (and much more). Details here.

    You should use the ActionBlock class and set the MaxDegreeOfParallelism of the ExecutionDataflowBlockOptions object. ActionBlock plays nicely with async/await, so even when your external calls are awaited, no new jobs will begin processing.

    ExecutionDataflowBlockOptions actionBlockOptions = new ExecutionDataflowBlockOptions
    {
         MaxDegreeOfParallelism = 10
    };
    
    this.sendToAzureActionBlock = new ActionBlock>(async items => await ProcessItems(items),
                actionBlockOptions);
    ...
    this.sendToAzureActionBlock.Post(itemsToProcess)
    

提交回复
热议问题