How to throttle multiple asynchronous tasks?

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

    Stephen Toub gives the following example for throttling in his The Task-based Asynchronous Pattern document.

    const int CONCURRENCY_LEVEL = 15;
    Uri [] urls = …;
    int nextIndex = 0;
    var imageTasks = new List>();
    while(nextIndex < CONCURRENCY_LEVEL && nextIndex < urls.Length)
    {
        imageTasks.Add(GetBitmapAsync(urls[nextIndex]));
        nextIndex++;
    }
    
    while(imageTasks.Count > 0)
    {
        try
        {
            Task imageTask = await Task.WhenAny(imageTasks);
            imageTasks.Remove(imageTask);
    
            Bitmap image = await imageTask;
            panel.AddImage(image);
        }
        catch(Exception exc) { Log(exc); }
    
        if (nextIndex < urls.Length)
        {
            imageTasks.Add(GetBitmapAsync(urls[nextIndex]));
            nextIndex++;
        }
    }
    

提交回复
热议问题