为什么不能在lock语句的主体内使用'await'运算符?

本文翻译自:Why can't I use the 'await' operator within the body of a lock statement?

The await keyword in C# (.NET Async CTP) is not allowed from within a lock statement. 锁定语句中不允许使用C#(.NET Async CTP)中的await关键字。

From MSDN : MSDN

An await expression cannot be used in a synchronous function, in a query expression, in the catch or finally block of an exception handling statement, in the block of a lock statement , or in an unsafe context. 等待表达式不能用于同步函数,查询表达式,异常处理语句的catch或finally块, 锁语句的块或不安全的上下文中。

I assume this is either difficult or impossible for the compiler team to implement for some reason. 我认为由于某种原因,对于编译器团队而言,这既困难又不可能。

I attempted a work around with the using statement: 我尝试了using语句:

class Async
{
    public static async Task<IDisposable> Lock(object obj)
    {
        while (!Monitor.TryEnter(obj))
            await TaskEx.Yield();

        return new ExitDisposable(obj);
    }

    private class ExitDisposable : IDisposable
    {
        private readonly object obj;
        public ExitDisposable(object obj) { this.obj = obj; }
        public void Dispose() { Monitor.Exit(this.obj); }
    }
}

// example usage
using (await Async.Lock(padlock))
{
    await SomethingAsync();
}

However this does not work as expected. 但是,这无法正常工作。 The call to Monitor.Exit within ExitDisposable.Dispose seems to block indefinitely (most of the time) causing deadlocks as other threads attempt to acquire the lock. 在ExitDisposable.Dispose中对Monitor.Exit的调用似乎无限期地(大部分时间)阻塞,导致死锁,因为其他线程试图获取该锁。 I suspect the unreliability of my work around and the reason await statements are not allowed in lock statement are somehow related. 我怀疑我的工作不可靠,而锁语句中不允许使用await语句的原因与某种原因有关。

Does anyone know why await isn't allowed within the body of a lock statement? 有谁知道为什么锁语句体内不允许等待?


#1楼

参考:https://stacko

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值