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

How should I structure try / finally when using SemaphorSlim with a cancellation token to handle OperationCancelledException correctly? In option A, cancellation of the token source throws an OperationCancelledException, but does not raise Release (). In option B, cancellation of the token source throws an OperationCancelledException and DOES raises 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(); } 
+7
source share
2 answers

Option A is more correct here. You do not need Release SemaphoreSlim when canceling, since you never purchase or increase your account. That way, you don't want to let out if your Wait call really failed.

From this MSDN Page when using Semaphore and Semaphore Slim :

It is the programmer's responsibility to ensure that the thread does not issue the semaphore too many times. For example, suppose a semaphore has a maximum number of two, and this stream A and stream B both enter the semaphore. If a programming error in thread B causes Release to be called twice, both calls are successful. The semaphore count is full, and when thread A eventually calls Release, a SemaphoreFullException is thrown.

+6
source

- Sorry for the late reply, hope this can help someone. Since we cannot guarantee the moment of cancellation, and when this code can be hit, we need to use option A. Then, in the finally item, check whether the cancellation token was used or not. If it was used, do not release the semaphore.

0
source

All Articles