【发布时间】:2015-01-08 09:47:17
【问题描述】:
我正在使用一个假设有一个静态实例的单例类,如下所示:
private static ISingletonClass _instance = null;
public static ISingletonClass GetInstance(string id = null)
{
if (_instance == null)
{
if (id != null)
{
_instance = new SingletonClass(id);
}
else
{
throw new NullReferenceException("id is missing!");
}
}
if (id != null && _instance.Id != id)
{
_instance = new SingletonClass(id); // changing instance
}
return _instance;
}
类中的所有其他代码都不是静态的(包括 Id 属性)。 在运行的早期,当还有一个线程时,我用一些 id 初始化单例,如下所示:
SingletonClass.GetInstance(<some_not_null_id>);
_instance 设置为不为空(已检查)。 后来我创建了一些线程来执行一些任务,其中需要从 SingletonClass 读取信息(不写入)。 根据我找到的任何文档以及 StackOverflow 中的答案,同一个实例应该可用于所有线程(我没有使用 [ThreadStatic] 或任何其他类似机制)。
但是,当尝试从线程内部不带参数的 GetInstance() 时,我得到 NullException(_instance 成员为 Null)。
我正在使用 .NET 4.5 版,并使用 VS2012。
有什么想法吗?
【问题讨论】:
-
旁注:
NullReferenceException是一个保留的异常,因此您不应该抛出它。 -
你得到你的空异常,带有“id is missing!”的那个。留言?
-
另一个旁注:你实现它的方式不再是单例了。
-
您的代码存在严重问题,无法将其视为 Singleton。当传递不同的 Id 时,它将创建不同的对象。它覆盖了以前编写的实例引用。
标签: c# .net multithreading thread-safety