时间:2019-03-17 标签:c#threadssynchronization
我需要使用锁对象,但它已被另一个线程使用。我希望等待锁定对象空闲,但不知道如何执行此操作。
我发现了这样的事情:
if(Monitor.TryEnter(_lock)
{
try
{
// do work
}
finally
{
Monitor.Exit(_lock);
}
}
但我只是检查并继续,但我希望等到锁对象空闲。
I need to use lock object, but it is already used by another thread. I wish to wait while the lock object will be free but have no idea how to do this.
I found sth like:
if(Monitor.TryEnter(_lock)
{
try
{
// do work
}
finally
{
Monitor.Exit(_lock);
}
}
But I it just check and go on, but I wish to wait until lock object is free.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要么使用这个:
或者 - 更好 -
lock
关键字:事实上,这些代码片段将生成相同的代码。编译器会将第二个代码翻译为第一个代码。然而,第二个是首选,因为它更具可读性。
更新:
该锁属于获取它的线程。这意味着可以嵌套使用
lock
语句:上面的代码不会阻塞。
Either use this:
or - more preferably - the
lock
keyword:In fact, those code snippets will generate the same code. The compiler will translate the second code into the first one. However, the second one is preferred because it is far more readable.
UPDATE:
The lock belongs to the thread it was acquired in. That means, nested usage of the
lock
statement is possible:The above code will not block.
您可以使用 Monitor.Enter
从文档:
You can use Monitor.Enter
From docs:
我同意@Daniel Hilgarth,
lock
语法是首选。关于你的问题:
根据 MSDN 描述:
锁定确保一个线程不会进入临界区,而另一个线程位于代码的临界区中。 如果另一个线程尝试输入锁定的代码,它将等待(阻塞)直到该对象被释放。
即您已经执行的代码已经执行了您想要的操作。
I agree with @Daniel Hilgarth, the
lock
syntax is preferred.Regarding your question:
As per the MSDN description:
lock ensures that one thread does not enter a critical section while another thread is in the critical section of code. If another thread attempts to enter a locked code, it will wait (block) until the object is released.
i.e. the code you have already does what you want it to.