Skip to main content
 首页 » 编程设计

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

2024年01月13日46mfryf

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。