尝试块之前/之后的SemaphoreSlim.WaitAsync [英] SemaphoreSlim.WaitAsync before/after try block
问题描述
我知道在同步世界中,第一个代码片段是正确的,但是WaitAsync和async/await魔术又如何呢?请给我一些.net内部.
await _semaphore.WaitAsync();
try
{
// todo
}
finally
{
_semaphore.Release();
}
或
try
{
await _semaphore.WaitAsync();
// todo
}
finally
{
_semaphore.Release();
}
根据MSDN,SemaphoreSlim.WaitAsync
可能会抛出:
-
ObjectDisposedException
-如果信号灯已被处置 -
ArgumentOutOfRangeException
-如果您选择接受int
且为负数(不包括-1)的重载
在两种情况下,SemaphoreSlim
都不会获取该锁,这使得在finally
块中释放它变得不必要.
要注意的一件事是,在第二个示例中,如果对象已放置或为null,则将执行finally块,并触发另一个异常或调用Release
,该异常可能首先没有获取任何要释放的锁./p>
最后,我将使用前者来确保与非异步锁的一致性,并避免在finally
块中出现异常
I know that in the sync world the first snippet is right, but what's about WaitAsync and async/await magic? Please give me some .net internals.
await _semaphore.WaitAsync();
try
{
// todo
}
finally
{
_semaphore.Release();
}
or
try
{
await _semaphore.WaitAsync();
// todo
}
finally
{
_semaphore.Release();
}
According to MSDN, SemaphoreSlim.WaitAsync
may throw:
ObjectDisposedException
- If the semaphore has been disposedArgumentOutOfRangeException
- if you choose the overload which accepts anint
and it is a negative number (excluding -1)
In both cases, the SemaphoreSlim
wont acquire the lock, which makes it unnessacery to release it in a finally
block.
One thing to note is if the object is disposed or null in the second example, the finally block will execute and either trigger another exception or call Release
which might have not acquired any locks to release in the first place.
To conclude, I would go with the former for consistency with non-async locks and avoiding exceptions in the finally
block
这篇关于尝试块之前/之后的SemaphoreSlim.WaitAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!