Search code examples
c#.netmultithreadingtask

Have a set of Tasks with only X running at a time


Let's say I have 100 tasks that do something that takes 10 seconds. Now I want to only run 10 at a time like when 1 of those 10 finishes another task gets executed till all are finished.

Now I always used ThreadPool.QueueUserWorkItem() for such task but I've read that it is bad practice to do so and that I should use Tasks instead.

My problem is that I nowhere found a good example for my scenario so could you get me started on how to achieve this goal with Tasks?


Solution

  • SemaphoreSlim maxThread = new SemaphoreSlim(10);
    
    for (int i = 0; i < 115; i++)
    {
        maxThread.Wait();
        Task.Factory.StartNew(() =>
            {
                //Your Works
            }
            , TaskCreationOptions.LongRunning)
        .ContinueWith( (task) => maxThread.Release() );
    }