Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c# - Keep running a specific number of tasks

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...