gpt4 book ai didi

c# - 为什么这个 SemaphoreSlim 会无限期地等待?

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:52 27 4
gpt4 key购买 nike

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

namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Task.Run(Test);
Console.ReadKey();
}

public static async Task Test()
{
var semahore = new SemaphoreSlim(0, 1);
Console.WriteLine("before");
await semahore.WaitAsync();
Console.WriteLine("after");
}
}
}

我创建了一个限制为 1 和当前值为 0 的信号量。它应该允许 1 个线程通过,对吗?为什么在这个例子中没有?

最佳答案

I create a semaphore with limit 1 and current value of 0. It should allow 1 thread to pass, right?

否 - 当前值为 0,与您所写的完全相同。

信号量值在等待时计数下降 - 计数实际上是“可获取的 token 数”。来自docs :

The count is decremented each time a thread enters the semaphore, and incremented each time a thread releases the semaphore. To enter the semaphore, a thread calls one of the Wait or WaitAsync overloads. To release the semaphore, it calls one of the Release overloads. When the count reaches zero, subsequent calls to one of the Wait methods block until other threads release the semaphore.

如果你想创建一个信号量,它会立即允许一个线程等待它并“通过”,你应该用初始值 1 来创建它,而不是 0。

关于c# - 为什么这个 SemaphoreSlim 会无限期地等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210048/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com