可以安全地在同一对象上使用 lock 和 monitor 吗? [英] Can lock and monitor be used on same object safely?

查看:24
本文介绍了可以安全地在同一对象上使用 lock 和 monitor 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:我想相互排除对对象的访问.

I have the following situation: I want to mutualy exclude access to an object.

到目前为止,我通常会使用锁对象

So far I normaly would use a lock object

object lockObject = new object();
...

method1: lock(lockObject) { CODE1 }

现在我还有一个可以从另一个线程调用的方法.不应该在未知时间内被阻塞,而是应该在定义的时间内给出答案.

Now I have also a method which can be called from another thread. It should not be blocked for unknown time, instead it should give an answer in a defined time.

在这种情况下,我将使用监视器,例如

In this case i would use a monitor, like

method2:
try{
   Monitor.TryEnter(lockObject , 20000, ref lockTaken);
   if (lockTaken) {CODE2}
}
catch(...){...}
finally
{
   if (lockTaken) Monitor.Exit(timerLock);
}

现在我的问题是:如果锁对象相同并且相互排斥,锁和监视器可以以这种方式混合,还是需要将每个锁都更改为监视器.

Now my question is: can lock and monitor be mixed in such a way if the lockobject is the same and mutually exclude each other, or would it be needed to change every lock to a monitor.

那么两次相同的令牌会被锁定",还是监视器会为对象创建另一个令牌然后锁定?

So would both times the same token be "locked", or would the monitor create another token for the object then the lock?

乍一看,我看不到应用程序同时在两者的代码中运行.但我不知道是否可能存在任何时序问题,其中 CODE1 和 CODE2 是并行执行的.

At a glimpse I cannot see that the aplication runs in code of both at the same time. But I don't know if any timing issues can exist, where CODE1 and CODE2 are executed in parallel.

推荐答案

lock (sync)
{
   return World();
}

会在中级语言中看到这一点.

Would look along the lines of this in Intermediate Language.

L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)
L_000c: call int32 Hello::World()
L_0011: stloc.0 
L_0012: leave.s L_001b
L_0014: ldloc.1 
L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)

所以应该没问题.它们在技术上是等效的.

So it should be okay. They are technically equivalent.

这篇关于可以安全地在同一对象上使用 lock 和 monitor 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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