锁(柜)和锁之间的区别(variable_which_I_am_using) [英] Difference between lock(locker) and lock(variable_which_I_am_using)
问题描述
我使用C#和放大器; .NET 3.5。在OptionA和OptionB之间的区别是什么?
I'm using C# & .NEt 3.5. What is the difference between the OptionA and OptionB ?
class MyClass
{
private object m_Locker = new object();
private Dicionary<string, object> m_Hash = new Dictionary<string, object>();
public void OptionA()
{
lock(m_Locker){
// Do something with the dictionary
}
}
public void OptionB()
{
lock(m_Hash){
// Do something with the dictionary
}
}
}
我开始在线程涉足(primarly创建一个缓存的多线程应用程序,不使用HttpCache类,因为它不能连接到网站),我看到了OptionA语法很多例子我在网上看到的,但我不明白,如果有的话,原因是做了OptionB。
I'm starting to dabble in threading (primarly for creating a cache for a multi-threaded app, NOT using the HttpCache class, since it's not attached to a web site), and I see the OptionA syntax in a lot of the examples I see online, but I don't understand what, if any, reason that is done over OptionB.
推荐答案
选项B使用对象进行保护,以营造一个关键部分。在一些情况下,这更清楚地进行通信的意图。如果持续使用,它保证只有一个被保护对象的关键部分将被激活的时间:
Option B uses the object to be protected to create a critical section. In some cases, this more clearly communicates the intent. If used consistently, it guarantees only one critical section for the protected object will be active at a time:
lock (m_Hash)
{
// Across all threads, I can be in one and only one of these two blocks
// Do something with the dictionary
}
lock (m_Hash)
{
// Across all threads, I can be in one and only one of these two blocks
// Do something with the dictionary
}
选项A是限制较少。它使用了一个次要目的是创建一个临界部分,用于要被保护的对象。如果使用多个二级对象,它可能有一次保护对象活动的多个关键部分。
Option A is less restrictive. It uses a secondary object to create a critical section for the object to be protected. If multiple secondary objects are used, it's possible to have more than one critical section for the protected object active at a time.
private object m_LockerA = new object();
private object m_LockerB = new object();
lock (m_LockerA)
{
// It's possible this block is active in one thread
// while the block below is active in another
// Do something with the dictionary
}
lock (m_LockerB)
{
// It's possible this block is active in one thread
// while the block above is active in another
// Do something with the dictionary
}
如果你只使用一个辅助对象选项A是等同于选择B。至于阅读code,选项B的意图更加清晰。如果你要保护多个对象,选项B是不是一个真正的选择。
Option A is equivalent to Option B if you use only one secondary object. As far as reading code, Option B's intent is clearer. If you're protecting more than one object, Option B isn't really an option.
这篇关于锁(柜)和锁之间的区别(variable_which_I_am_using)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!