Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
145 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...