保持运行的任务的一个特定数定数、任务

2023-09-03 01:48:07 作者:Dreamkiller梦境杀手

我一直在努力做到这一点:

I have been trying to do this:

创建N的任务来执行和保持运行TAKS此数目的一段时间,在此情况下 一个任务敲定,那么我应该开始一个新的任务,以保持任务数相同。

Create 'N' Task to execute and keep running this number of taks for a period of time, in that case the one task finalize, then i should start a new task to keep the same number of task.

我不知道这是可能的处理与的TaskScheduler或我要创建一个自定义的TaskScheduler。

I dont know if is this possible to handle with TaskScheduler or i have to create a custom TaskScheduler.

另一种选择,我认为可以工作的,使用TPL数据流生产者 - 消费者当任务完成,然后的TaskScheduler采取了新的任务由生产商产生。

Another option i think could work is , use TPL DataFlow Producer-Consumer when the task finish then taskscheduler take a new task generate by producer.

现在的问题是:如何创建一个新的任务时,一个成品保持任务相同数量的

The question is: how can i create a new task when one finished to keep the same number of tasks?

推荐答案

这code将继续运行 numTasks 任务并行。

This code will keep running numTasks Tasks in parallel.

int numTasks = 5;
SemaphoreSlim semaphore = new SemaphoreSlim(numTasks);
while(true)
{
    semaphore.Wait();
    Task.Run(() =>
        {
            DoSomething();
        })
        .ContinueWith(_ => semaphore.Release());
}
 
精彩推荐