Semaphoreslim locking method

Asked

Viewed 98 times

2

I am using Semaphoreslim to make the "lock" of some methods of my Web-API, until it worked correctly but there are times when these same methods get totally stuck, by Postman when I run gets a loading and after some time returns the error.

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

Just and another method is using Semaphoreslim’s Wait. The other methods I’m not doing this locking. Does anyone have any idea what it might be?

1 answer

0

The behavior is correct. When called await semaphoreSlimScheduling.Waitasync() the thread will be suspended until the return of the task. Depending on what you’re doing, it can take a while or even fail to get the lock (Postman intermittence). I suggest two things:

  • Set a timeout for the lock (overload of the Waitasync() method), avoiding that the task is waiting infinitely
  • Assign Waitasync return and check whether it returns true (lock acquired) or false (lock failure).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.