尝试块之前/之后的SemaphoreSlim.WaitAsync [英] SemaphoreSlim.WaitAsync before/after try block

查看:257
本文介绍了尝试块之前/之后的SemaphoreSlim.WaitAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在同步世界中,第一个代码片段是正确的,但是WaitAsync和async/await魔术又如何呢?请给我一些.net内部.

await _semaphore.WaitAsync();
try
{
    // todo
}
finally
{
    _semaphore.Release();
}

try
{
    await _semaphore.WaitAsync();
    // todo
}
finally
{
    _semaphore.Release();
}

解决方案

根据MSDN,SemaphoreSlim.WaitAsync可能会抛出:

  1. ObjectDisposedException-如果信号灯已被处置

  2. 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:

  1. ObjectDisposedException - If the semaphore has been disposed

  2. ArgumentOutOfRangeException - if you choose the overload which accepts an int 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆