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();
}
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.
-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.
精彩评论