SemaphoreSlim locking method

2

I'm using SemaphoreSlim to "lock" some of my Web-API's methods until it worked correctly however there are times when these same methods get stuck completely, by postman when I run it gets a loading and after some time returns the error.

Follow the code

public class ApiController : Controller
{
    static SemaphoreSlim semaphoreSlimScheduling = new SemaphoreSlim(1);

    ...//outros métodos

    [HttpPost]
    public async Task<JsonResult> ConfirmScheduling(FormCollection collection)
    {
        try
        {
            await semaphoreSlimScheduling.WaitAsync();

            //código....

            semaphoreSlimScheduling.Release();
            return Json(new { error = false, message = "Sucesso" });
        }
        catch (Exception ex)
        {
            semaphoreSlimScheduling.Release();
            return Json(new { error = true, message = ex.Message });
        }
    }   
}

Only one other method is using the SemaphoreSlim wait. The other methods I'm not doing this locking. Anyone have an idea what it can be?

    
asked by anonymous 30.05.2018 / 04:27

1 answer

0

The behavior is correct. When call await semaphoreSlimScheduling.WaitAsync () the thread will be suspended until the task returns. Depending on what you are doing, you may experience delay or even failure to get the lock (postman blinking). I suggest two things:

  • Put a timeout for the lock (WaitAsync () method overload, preventing the task from waiting infinitely
  • Assign the WaitAsync return and check whether it returns true (lock acquired) or false (failure to lock).
05.06.2018 / 02:35