Search code examples
c#asynchronoustaskhttpwebrequestlimit

C# limit number of async calls


So I have this code:

var tasks = Enumerable.Range(0, maxsize).Select(index => CallRequestsAsync(param1[index], param2[index]));
            Task.WaitAll(tasks.ToArray());

This code calls a bunch of async tasks that are doing webrequests and other work. I want to limit the number of maximum active running tasks at a time,lets say 50 at a time.Then,if one finishes work,a new one will be called,so basicly there will always be 50 running async tasks at a time until it finishes my list. So how can I accomplish that by using the format above? The index is an int,used to retrieve paramaters from external variables.


Solution

  • I think you are doing something similar to below:

            var maxsize = 50;
            var tasks = new List<Task>();
            for (int index = 0; index < int.MaxValue; index++)
            {
                tasks.Add(CallRequestsAsync(param1[index], param2[index]));
                if (tasks.Count > maxsize)
                    Task.WaitAny(tasks.ToArray());
                tasks.RemoveAll(x => x.IsCompleted);
            }