直接贴代码了:

   using System;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;

    class TaskSample
    {
        public static void Do()
        {
            Run();
        }

        private static readonly SemaphoreSlim _mutex = new SemaphoreSlim(5);

        private static void Run()
        {
            var allTasks = Enumerable.Range(1, 10000000).Select(id => DoWorkAsync(id));
            //await Task.WhenAll(tasks);
            Task.WaitAll(allTasks.ToArray());
        }

        private static async Task DoWorkAsync(int id)
        {
            await _mutex.WaitAsync();
            try
            {
                Console.WriteLine($"Starting Work {id}");
                await HttpClientGetAsync();
                Console.WriteLine($"Finished Work {id}");
            }
            finally
            {
                _mutex.Release();
            }
        }

        static async Task HttpClientGetAsync()
        {
            await Task.Delay(2000);
        }

    }

 

运行截图:

C# 中一个限制 Task 并发执行的数量的示例

 

谢谢浏览!

相关文章:

  • 2022-12-23
  • 2023-02-04
  • 2021-12-19
  • 2021-07-28
  • 2021-12-06
  • 2021-05-16
  • 2021-12-26
  • 2022-12-23
猜你喜欢
  • 2021-10-16
  • 2023-04-04
  • 2021-11-24
  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
  • 2022-01-31
相关资源
相似解决方案