我的 asp mvc 应用程序中有一个类保存一些“全局”数据。它是作为单例实现的。它看起来像这样:
class InfoStrings
{
public List<string> strings = new List<string>();
static InfoStrings me = null;
private InfoStrings()
{ }
public static InfoStrings GetMe()
{
if(me == null)
me = new InfoStrings();
return me;
}
}
现在从 Controller 的代码中,我通过像这样锁定它来访问这个类:
lock (InfoStrings.GetMe())
{
...
}
好的,2 个问题:
1)理论上,我的 InfoStrings 对象可以被垃圾回收吗?
2)我在那里正确锁定了吗?
请您参考如下方法:
1)Theoretically, can my InfoStrings object be garbage collected?
不,它是一个静态字段,一旦分配就不会被垃圾回收。
2)Am I doing proper locking there?
我建议您锁定私有(private)静态对象:
private static object _syncRoot = new object();
...
lock (_syncRoot)
{
var instance = InfoStrings.GetMe();
}
您可能还会找到 following article在 C# 中实现单例模式时很有用。示例:
public sealed class InfoStrings
{
private InfoStrings()
{
}
public static InfoStrings Instance
{
get { return Nested.instance; }
}
private class Nested
{
static Nested()
{
}
internal static readonly InfoStrings instance = new InfoStrings();
}
}
然后你不需要锁定来获取实例:
var instance = InfoStrings.Instance;
