public class Manager {
private static Manager _one;
private static Manager _two;
private static object Obj_Lock_one = new object();
private static object Obj_Lock_two = new object();//Do I need Obj_Lock_two here ?
public static Manager GetOne ()
{
if (_one == null)
{
lock (Obj_Lock_one)
{
if (_one == null)
{
_one = new Manager();
}
}
}
return _one;
}
public static Manager GetTwo ()
{
if (_two == null)
{
lock (Obj_Lock_two) //Do I need Obj_Lock_two here ?
{
if (_two == null)
{
_two = new Manager();
}
}
}
return _two;
}
}
我需要第二个对象来锁定吗?在 GetTwo 方法中,我应该使用“lock(Obj_Lock_one)”还是“lock(Obj_Lock_two)”
如果我只用一个obj来加锁,我想可能只会阻塞一个thred...
那么正确的方法是什么?
最佳答案
Do I need a second obj to lock?
如果两个线程同时调用 GetOne()
,在这里使用第二个锁对象将稍微提高性能。和 GetTwo()
第一次同时。换句话说:您可能无法衡量差异。
SO what is the correct way?
不要重新发明轮子。废弃你的代码并使用 Lazy initialization with Lazy<T>
相反,它是线程安全的并自动处理所有这些线程同步问题:
public sealed class Manager
{
private static readonly Lazy<Manager> lazyOne = new Lazy<Manager>(() => new Manager());
private static readonly Lazy<Manager> lazyTwo = new Lazy<Manager>(() => new Manager());
public static Manager GetOne() { return lazyOne.Value; }
public static Manager GetTwo() { return lazyTwo.Value; }
}
关于c# - 我有一个 Singleton 类,但返回两个。我需要两个 lok 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429210/