SemaphoreSlim.WaitAsync before / after try block

I know that in the world of synchronization, the first fragment is right, but what about WaitAsync and async / await magic? Please give me some internal .net components.

await _semaphore.WaitAsync();
try
{
    // todo
}
finally
{
    _semaphore.Release();
}

or

try
{
    await _semaphore.WaitAsync();
    // todo
    }
    finally
    {
        _semaphore.Release();
    }
}
+4
source share
3 answers

According to MSDN, it SemaphoreSlim.WaitAsynccan throw:

  • ObjectDisposedException - If the semaphore was located

  • ArgumentOutOfRangeException- if you choose an overload that accepts int, and that is a negative number (excluding -1)

In both cases, SemaphoreSlimit will not receive a lock, which makes it unable to release it in the block finally.

, , finally Release, , , .

finally

+7

WaitAsync, , a Release , . .

( , NullReferenceException), :

try
{
    await _semaphore.WaitAsync();
}
catch
{
    // handle
}

try
{
    // todo
}
finally
{
    _semaphore.Release();
}
+2

.

lock(){}:

, no-op , , . , , , , , . , . (https://blogs.msdn.microsoft.com/ericlippert/2009/03/06/locks-and-exceptions-do-not-mix/)

, lock , , SemaphoreSlim.WaitAsync() try, , ( Monitor.Enter, ). SemaphoreSlim .

using :

using (Font font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

:

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

noop Monitor.Enter() try, using, ?

, AsyncSemaphore https://github.com/Microsoft/vs-threading/blob/81db9bbc559e641c2b2baf2b811d959f0c0adf24/src/Microsoft.VisualStudio.Threading/AsyncSemaphore.cs

and extensions for SemaphoreSlim https://github.com/StephenCleary/AsyncEx/blob/02341dbaf3df62e97c4bbaeb6d6606d345f9cda5/src/Nito.AsyncEx.Coordination/SemaphoreSlimExtensions.cs

also interesting.

0
source

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


All Articles