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

三世轮回 提交于 2021-01-29 05:43:56

问题


I am building an ASP.NET (.NET Framework) application in C# I am making API calls to a backend service called "LinuxDocker" and I am trying to limit the number of 12 concurrent calls to it from the ASP.NET application. Here is the code I wrote:

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();
    }
}

Then when I call my backend service, I do so like this:

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

So it seems like this should limit to 12 concurrent calls, however when I test it from an integration test with 100 simultaneous calls, it basically only allows 1 request at a time to go through, not 12 calls at a time to go through.

The service is running on IIS on Windows Server 2016 and .NET Framework 4.7.

I have read this code many times and can't figure out why it doesn't work.

Any help would be greatly appreciated.


回答1:


Possibly your backend is being served up by multiple w3wp.exe worker processes. Because your semaphore is created without a name it is a "local" semaphore (local to each process) as opposed to a "global" semaphore (system-wide):

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



来源:https://stackoverflow.com/questions/57667900/c-sharp-semaphores-not-working-as-expected-cannot-figure-out-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!