Monitor.Enter and Monitor.Exit

简介:

 C#中的Lock语句实际上是对方法Monitor.Enter,Monitor.Exit和try finally语句块的语法快捷方式。

 {

static readonly object _locker = new object();

static int _val1, _val2;

static void Go()

{

lock (_locker)

{

if (_val2 != 0) Console.WriteLine (_val1 / _val2);

_val2 = 0;

}

}

}

这段代码使用了Lock语句。对于Go方法真正的做的事情其实是下面的代码:

 

Monitor.Enter (_locker);

try

{

if (_val2 != 0) Console.WriteLine (_val1 / _val2);

_val2 = 0;

}

finally { Monitor.Exit (_locker); }

对于同一对象,调用Monitor.Exit而不调用Monitor.Enter会引发异常。

上面的代码有一点瑕疵。如果在Monitor.Enter执行的时候发生异常(尽管不太可能),此时finally方法无法执行,这时候这个锁就无法被释放了。

基于上面的缺陷,.NET 4.0 重载了Monitor.Enter方法

public static void Enter (object obj, ref bool lockTaken);

当且仅当Monitor.Enter有异常的时候,lockTaken的值会被设为False。

下面的代码是.NET 4.0中的Monitor使用的模式:(也就是Lock语句在.net 4.0中被翻译成的语句)

bool lockTaken = false;

try

{

Monitor.Enter (_locker, ref lockTaken);

// Do your stuff...

}

finally { if (lockTaken) Monitor.Exit (_locker); }





















本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/511224 ,如需转载请自行联系原作者


相关文章
|
26天前
Another app is currently holding the yum lock; waiting for it to exit
Another app is currently holding the yum lock; waiting for it to exit
9 0
|
网络安全 开发工具
【解决方案】A session ended very soon after starting. Check that the command in profile “XXX” is correct.
【解决方案】A session ended very soon after starting. Check that the command in profile “XXX” is correct.
782 0
【解决方案】A session ended very soon after starting. Check that the command in profile “XXX” is correct.
|
资源调度
yarn start error Command failed with exit code 1解决
yarn start error Command failed with exit code 1解决
873 0
|
C++
ERROR: Command errored out with exit status 1:
ERROR: Command errored out with exit status 1:
209 0
ERROR: Command errored out with exit status 1:
|
监控 安全 网络协议
[知识小节]Process Monitor介绍(上)
[知识小节]Process Monitor介绍
954 0
[知识小节]Process Monitor介绍(上)
|
存储 监控 安全
[知识小节]Process Monitor介绍(下)
[知识小节]Process Monitor介绍
895 0
[知识小节]Process Monitor介绍(下)
|
存储 Java 程序员
Monitor
我们Java程序员编码时谈论的最多的两个字就是对象,Java中几乎所有的技术都是围绕对象展开。本文将要讲述的Monitor并不是Java对象,而是在操作系统中关联的“对象”,Monitor是Java重量级锁synchronized实现的关键,因此学习Java单机同步机制就离不开对Monitor的剖析。Monitor从Java层面经常被人们称为监视器锁,而在操作系统层面称为管程。
436 2
Monitor
|
测试技术