我需要一次完成5个任务并行执行的最大2个任务。 因此,一旦某个任务完成,下一个应该运行,直到没有待处理的任务。Task.Factory.StartNew的随机任务不启动
我使用的是一个solution by L.B.,它涉及使用信号来跨任务进行同步。
void LaunchTaskPool()
{
SemaphoreSlim maxThreadSemaphore = new SemaphoreSlim(2); //Max 2 tasks at a time.
for (int i = 0; i < 5; i++) //loop through 5 tasks to be assigned
{
maxThreadSemaphore.Wait(); //Wait for the queue
Console.WriteLine("Assigning work {0} ", i);
Task t = Task.Factory.StartNew(() =>
{
DoWork(i.ToString()); // assign tasks
}, TaskCreationOptions.LongRunning
)
.ContinueWith(
(task) => maxThreadSemaphore.Release() // step out of the queue
);
}
}
void DoWork(string workname)
{
Thread.Sleep(100);
Console.WriteLine("--work {0} starts", workname);
Thread.Sleep(1000);
Console.WriteLine("--work {0} finishes", workname);
}
问题是,一些随机任务甚至不会启动。例如在这里工作1和3从来没有开始工作,并得到了4运行两次:
我尝试添加Task.WaitAll()的建议here,但它并没有帮助。
在此先感谢您的建议!
君士坦丁。
https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop -variable-considered-harmful/ –