How should I structure the try/finally when using a SemaphorSlim with cancellation token so that OperationCancelledException is handled correctly? In Option A, cancelling the token source throws OperationCancelledException but does not call Release(). In Option B, cancelling the token source throws OperationCancelledException and DOES call Release().
// option A:
_semaphorSlim.Wait( _cancellationTokenSource.Token );
try
{
// do work here
}
finally
{
_semaphorSlim.Release();
}
// option B:
try
{
_semaphorSlim.Wait( _cancellationTokenSource.Token );
// do work here
}
finally
{
_semaphorSlim.Release();
}
Option A is more correct here. You do not need to Release
the SemaphoreSlim
when you cancel, as you never actually acquire and increment its count. As such, you don't want to release unless your Wait
call actually succeeded.
From this MSDN Page on using Semaphore and SemaphoreSlim:
It is the programmer's responsibility to ensure that a thread does not release the semaphore too many times. For example, suppose a semaphore has a maximum count of two, and that thread A and thread B both enter the semaphore. If a programming error in thread B causes it to call Release twice, both calls succeed. The count on the semaphore is full, and when thread A eventually calls Release, a SemaphoreFullException is thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With