我需要一次完成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/ –