Keep running a specific number of tasks

这一生的挚爱 提交于 2019-12-17 20:30:50

问题


I have been trying to do this:

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.

I dont know if is this possible to handle with TaskScheduler or i have to create a custom 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?


回答1:


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



回答2:


Task scheduler could be used to run an executable that you could use to perform a set of work/tasks. Alternatively, you could simply create a windows service...



来源:https://stackoverflow.com/questions/21052853/keep-running-a-specific-number-of-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!