发布:2021/3/5 17:20:32作者:管理员 来源:本站 浏览次数:1299
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);
}
}
运行截图:
谢谢浏览!
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4