Keep running a specific number of tasks

前端 未结 2 870
太阳男子
太阳男子 2020-12-11 12:20

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 sho

2条回答
  •  無奈伤痛
    2020-12-11 13:01

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

提交回复
热议问题