Reputation: 36597
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();
}
Upvotes: 11
Views: 2082
Reputation: 257
-Sorry for the late reply, hopefully it might help someone. Since we can't guarantee the moment of cancellation and when this code might be hit we need to use the option A. Then in finally clause check whether cancellation token has been used or not. If it has been used then don't release the semaphore.
Upvotes: 0
Reputation: 564751
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.
Upvotes: 11