gpt4 book ai didi

.net - SemaphoreSlim.Wait( CancellationToken ) 对OperationCancelledException 进行正确的try/finally 吗?

转载 作者:行者123 更新时间:2023-12-02 22:57:40 32 4
gpt4 key购买 nike

当使用带有取消标记的 SemaphorSlim 时,我应该如何构造 try/finally 以便正确处理 OperationCancelledException?在选项A中,取消 token 源会抛出OperationCancelledException,但不会调用Release()。在选项B中,取消 token 源会抛出OperationCancelledException并且确实会调用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();
}

最佳答案

这里选项A更正确。取消时无需释放SemaphoreSlim,因为您从未真正获取并增加其计数。因此,除非 Wait 调用实际成功,否则您不想释放。

从此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.

关于.net - SemaphoreSlim.Wait( CancellationToken ) 对OperationCancelledException 进行正确的try/finally 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6233774/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com