【发布时间】:2019-10-02 00:48:43
【问题描述】:
我以为我了解 SemaphoreSlim,但我想我需要一些帮助。如果我声明一个 maxCount 为 2 的信号量,那么我假设在循环内每次调用 WaitAsync() 时,信号量计数最多会增长到 2,最多允许一次运行两个任务,但它只运行即使我在每个任务结束时释放信号量,也一次一个。有人能解释一下为什么这段代码一次运行一个任务吗?
class Program
{
static SemaphoreSlim _loopThrottle = new SemaphoreSlim(1, 2);
static async Task Main(string[] args)
{
for (int taskID = 1; taskID <= 10; taskID++)
{
await _loopThrottle.WaitAsync();
var t = SomeFunctionAsync(taskID);
}
Console.ReadLine();
}
private async static Task SomeFunctionAsync(int taskID)
{
await Task.Delay(1000);
Console.WriteLine(taskID);
_loopThrottle.Release();
}
}
【问题讨论】:
标签: multithreading .net-core task semaphore