本文翻译自: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关键字。
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? 有谁知道为什么锁语句体内不允许等待?