How to throttle multiple asynchronous tasks?

前端 未结 6 1382
野趣味
野趣味 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:19

    First, abstract away from threads. Especially since your operation is asynchronous, you shouldn't be thinking about "threads" at all. In the asynchronous world, you have tasks, and you can have a huge number of tasks compared to threads.

    Throttling asynchronous code can be done using SemaphoreSlim:

    static async Task DoSomething(int n);
    
    static void RunConcurrently(int total, int throttle) 
    {
      var mutex = new SemaphoreSlim(throttle);
      var tasks = Enumerable.Range(0, total).Select(async item =>
      {
        await mutex.WaitAsync();
        try { await DoSomething(item); }
        finally { mutex.Release(); }
      });
      Task.WhenAll(tasks).Wait();
    }
    

提交回复
热议问题