How to throttle multiple asynchronous tasks?
问题 I have some code of the following form: static async Task DoSomething(int n) { ... } static void RunThreads(int totalThreads, int throttle) { var tasks = new List<Task>(); for (var n = 0; n < totalThreads; n++) { var task = DoSomething(n); tasks.Add(task); } Task.WhenAll(tasks).Wait(); // all threads must complete } Trouble is, if I don't throttle the threads, things start falling apart. Now, I want to launch a maximum of throttle threads, and only start the new thread when an old one is