显示器VS锁 [英] Monitor vs lock
问题描述
当它是适当的,以使用显示器
类或C#中的锁定
关键字线程安全?
When is it appropriate to use either the Monitor
class or the lock
keyword for thread safety in C#?
编辑:
它似乎离答案至今的锁定
短手的一系列调用显示器
类。到底是什么锁调用短手?或者更明确地说,
It seems from the answers so far that lock
is short hand for a series of calls to the Monitor
class. What exactly is the lock call short-hand for? Or more explicitly,
class LockVsMonitor
{
private readonly object LockObject = new object();
public void DoThreadSafeSomethingWithLock(Action action)
{
lock (LockObject)
{
action.Invoke();
}
}
public void DoThreadSafeSomethingWithMonitor(Action action)
{
// What goes here ?
}
}
更新
感谢大家的帮助:我已经发布了一个又一个的问题作为后续行动,一些你提供的所有信息。既然你似乎深谙这方面,我已经发布的链接:<一href="http://stackoverflow.com/questions/4979331/what-is-wrong-with-this-solution-to-locking-and-managing-locked-exceptions">What不对这个解决方案,锁定和管理锁定例外?
Thank you all for your help : I have posted a another question as a follow up to some of the information you all provided. Since you seem to be well versed in this area, I have posted the link: What is wrong with this solution to locking and managing locked exceptions?
推荐答案
这个在他的博客埃里克利珀会谈: <一href="http://blogs.msdn.com/b/ericlippert/archive/2009/03/06/locks-and-exceptions-do-not-mix.aspx">Locks和异常不混合
Eric Lippert talks about this in his blog: Locks and exceptions do not mix
相当于code C#4.0和更早的版本是不同的。
The equivalent code differs between C# 4.0 and earlier versions.
在C#4.0,它是:
bool lockWasTaken = false;
var temp = obj;
try
{
Monitor.Enter(temp, ref lockWasTaken);
{ body }
}
finally
{
if (lockWasTaken) Monitor.Exit(temp);
}
它依赖于 Monitor.Enter
原子设置标志,采取了锁的时候。
It relies on Monitor.Enter
atomically setting the flag when the lock is taken.
和以前它是:
var temp = obj;
Monitor.Enter(temp);
try
{
body
}
finally
{
Monitor.Exit(temp);
}
这依赖于在 Monitor.Enter
被抛出也不例外,在尝试
。我认为,在调试code这种情况下被侵犯,因为编译器插入它们之间的NOP,从而取得这些可能的线程流产。
This relies on no exception being thrown between Monitor.Enter
and the try
. I think in debug code this condition was violated because the compiler inserted a NOP between them and thus made thread abortion between those possible.
这篇关于显示器VS锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!