Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SemaphoreSlim.Wait( CancellationToken ) proper try/finally for OperationCancelledException?

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();
}
like image 939
SFun28 Avatar asked Jun 04 '11 00:06

SFun28


1 Answers

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.

like image 93
Reed Copsey Avatar answered Oct 09 '22 12:10

Reed Copsey