C#锁定和异步方法 [英] C# Lock and Async Method
问题描述
我不清楚(并且找不到足够清晰的文档):在异步方法中使用lock关键字时:如果对象已被阻塞,线程将被阻塞,还是返回挂起状态的任务(不是阻塞线程,并在释放锁定时返回)?
I am not clear (and can't find documentation clear enough): when using the lock keyword in an async method: will the thread be blocked if the object is already blocked or will it return a task in suspended state (not blocking the thread, and returning when the lock is released)?
在下面的代码中,该行会阻塞线程吗?如果它阻塞了线程(这是我的想法),是否有一个标准的不阻塞解决方案?我正在考虑使用 AsyncLock ,但是首先我想尝试一些标准的东西
In the code below, will the line block the thread? If it blocks the thread (which is what I think), is there an standard not blocking solution? I am considering using AsyncLock, but first I wanted to try for something standard.
谢谢.
private object myLock = new object();
private async Task MyMethod1(){
lock (myLock ) {// <---- will this line cause a return of the current method as an Await method call would do if myLock was already locked.
....
}
}
// other methods that lock on myLock
推荐答案
不会.
lock
是Monitor.Enter
和Monitor.Exit
的语法糖. lock
将继续在方法中执行,直到释放锁定为止.它在任何形式,形状或形式上都不像await
.
lock
is syntactic sugar for Monitor.Enter
and Monitor.Exit
. lock
will keep execution in the method until the lock is released. It does not function like await
in any way, shape or form.
这篇关于C#锁定和异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!