How to throttle multiple asynchronous tasks?

前端 未结 6 1371
野趣味
野趣味 2020-12-03 12:36

I have some code of the following form:

static async Task DoSomething(int n) 
{
  ...
}

static void RunThreads(int totalThreads, int throttle) 
{
  var task         


        
6条回答
  •  北海茫月
    2020-12-03 13:35

    If I understand correctly, you can start tasks limited number of tasks mentioned by throttle parameter and wait for them to finish before starting next..

    To wait for all started tasks to complete before starting new tasks, use the following implementation.

    static async Task RunThreads(int totalThreads, int throttle)
    {
        var tasks = new List();
        for (var n = 0; n < totalThreads; n++)
        {
            var task = DoSomething(n);
            tasks.Add(task);
    
            if (tasks.Count == throttle)
            {
                await Task.WhenAll(tasks);
                tasks.Clear();
            }
        }
        await Task.WhenAll(tasks); // wait for remaining
    }
    

    To add tasks as on when it is completed you can use the following code

    static async Task RunThreads(int totalThreads, int throttle)
    {
        var tasks = new List();
        for (var n = 0; n < totalThreads; n++)
        {
            var task = DoSomething(n);
            tasks.Add(task);
    
            if (tasks.Count == throttle)
            {
                var completed = await Task.WhenAny(tasks);
                tasks.Remove(completed);
            }
        }
        await Task.WhenAll(tasks); // all threads must complete
    }
    

提交回复
热议问题