I need to have 5 tasks completed in parallel with max 2 executed at a time. So, as soon as some task is finished, the next should be run - up until there are no tasks pending.
I'm using a solution by L.B. which involves using semaphores for synchronization across tasks.
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);
}
The problem is that some random tasks would not even start. For example here Work 1 and 3 never started and Work 4 got run twice:
I tried adding Task.WaitAll() as suggested here, but it didn't help.
thanks in advance for your suggestions!
Constantine.