Await multiple async Task while setting max running task at a time

后端 未结 4 992
失恋的感觉
失恋的感觉 2020-12-19 12:19

So I just started to try and understand async, Task, lambda and so on, and I am unable to get it to work like I want. With the code below I want for it to lock btnDoWebReque

4条回答
  •  情书的邮戳
    2020-12-19 12:52

    I have created an extension method for this.

    It can be used like this:

    var tt = new List>()
    {
        () => Thread.Sleep(300), //Thread.Sleep can be replaced by your own functionality, like calling the website
        () => Thread.Sleep(800),
        () => Thread.Sleep(250),
        () => Thread.Sleep(1000),
        () => Thread.Sleep(100),
        () => Thread.Sleep(200),
    };
    await tt.WhenAll(3); //this will let 3 threads run, if one ends, the next will start, untill all are finished.
    

    The extention method:

    public static class TaskExtension
    {
        public static async Task WhenAll(this List> actions, int threadCount)
        {
            var _countdownEvent = new CountdownEvent(actions.Count);
            var _throttler = new SemaphoreSlim(threadCount);
    
            foreach (Func action in actions)
            {
                await _throttler.WaitAsync();
    
                Task.Run(async () =>
                {
                    try
                    {
                        await action();
                    }
                    finally
                    {
                        _throttler.Release();
                        _countdownEvent.Signal();
                    }
                });
            }
    
            _countdownEvent.Wait();
        }
    }
    

提交回复
热议问题