C# 信号量未按预期工作,无法弄清楚原因

C# Semaphores not working as expected, cannot figure out why

我正在用 C# 构建一个 ASP.NET (.NET Framework) 应用程序 我正在 API 调用一个名为 "LinuxDocker" 的后端服务,我正在尝试限制ASP.NET 应用程序对其进行了 12 次并发调用。这是我写的代码:

private static Semaphore LinuxDockerSemaphore = new Semaphore(12, 12);

public static SemaphoreWaiter WaitForLinuxDocker(int timeoutMS = -1)
{
      return new SemaphoreWaiter(LinuxDockerSemaphore, timeoutMS);
}

public class SemaphoreWaiter : IDisposable
{
    Semaphore Slim;

    public SemaphoreWaiter(Semaphore slim, int timeoutMS = -1)
    {
        Slim = slim;
        Slim.WaitOne(timeoutMS);
    }

    public void Dispose()
    {
        Slim.Release();
    }
}

然后当我调用我的后端服务时,我会这样做:

using (ConcurrencyManager.WaitForLinuxDocker())
{
      // Call backend service here
}

所以这似乎应该限制为 12 个并发调用,但是当我通过 100 个并发调用的集成测试对其进行测试时,它基本上一次只允许 1 个请求通过,而不是一次 12 个调用要通过。

该服务在 Windows Server 2016 和 .NET Framework 4.7 上的 IIS 上 运行。

我已经多次阅读这段代码,但无法弄清楚为什么它不起作用。

如有任何帮助,我们将不胜感激。

可能您的后端由多个 w3wp.exe 工作进程提供服务。因为您的信号量是在没有名称的情况下创建的,所以它是“本地”信号量(每个进程的本地)而不是“全局”信号量(系统范围):

Semaphores are of two types: local semaphores and named system semaphores. If you create a Semaphore object using a constructor that accepts a name, it is associated with an operating-system semaphore of that name. Named system semaphores are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create multiple Semaphore objects that represent the same named system semaphore, and you can use the OpenExisting method to open an existing named system semaphore.

A local semaphore exists only within your process. It can be used by any thread in your process that has a reference to the local Semaphore object. Each Semaphore object is a separate local semaphore.

REF:Semaphore Class