.NET: using Mutex to ensure that a web service is called only once at a time

I use Mutex to make sure that the web service only works once at a time, but I cannot get it 100% with WaitOnce and ReleaseMutex.

I have it:

    private static Mutex mutex = new Mutex();

    [WebMethod]
    public bool TriggerAll()
    {
        bool ranJobs = false;
        try
        {
            if (mutex.WaitOne(0, false))
            {
                Thread.Sleep(10000); // simulate a long operation
                ranJobs = true;
            }
        }
        finally
        {
            mutex.ReleaseMutex();   
        }
        return ranJobs;
    }

I try to access the web service twice immediately, the second call does not return false, but I get the application exception from mutex.ReleaseMutex ("the object synchronization method was called from onsyncronized codeblock" - roughly translated from Swedish)

What is the best way to do this?

+3
source share
1 answer

ReleaseMutex, WaitOne true. ReleaseMutex, :

    if (mutex.WaitOne(0, false))
    {
        try
        {
            Thread.Sleep(10000); // simulate a long operation
            ranJobs = true;
        }
        finally
        {
            mutex.ReleaseMutex();   
        }
    }

AppDomains? , CLR- ( Monitor.TryEnter) .

+7

Source: https://habr.com/ru/post/1710070/


All Articles