问题描述
我有一个Windows服务,其中包含一个单例,该单例又使用一些记录器,消息队列侦听器等.这些类实现IDisposable
.我应该在单例本身中实现IDisposable
还是做其他事情以确保服务停止/崩溃后,使用本机资源一切正常?单例是这样实现的:
I have a windows service, which contains a singleton which in turn uses some loggers, message queue listeners and so on. Those classes implements IDisposable
. Should I implement IDisposable
in singleton itself or do something else to ensure that after service stop/crashing everything will be okay with native resources?The singleton is implemented like this:
public class Temp
{
private static readonly Lazy<Temp> instance = new Lazy<Temp>(() => new Temp());
private Temp()
{
// create IDisposable objects which use native resources
}
public static Temp Instance
{
get
{
return instance.Value;
}
}
}
推荐答案
我宁愿不实施 IDisposable
在单例上:IDisposable
激发开发人员以处置(单个)实例:
I'd rather not implement IDisposable
on singleton: IDisposable
provokes developer to Dispose the (single) instance:
using(var temp = Temp.Instance) {
...
}
导致在应用程序的其他部分中发生(可能)崩溃(因为已丢弃单个Temp
实例):
which leads to (possible) crash in some other part of the application (since the single Temp
instance has been disposed):
Temp.Instance.SomeFucntion(); // <- possible fail, since Temp.Instanceis disposed
在极少数情况下,如果您必须发布所需的某些资源,我会使用ProcessExit
事件
In some rare case if you have to release some resouces aquired, I'd use ProcessExit
event
public class Temp {
private static readonly Lazy<Temp> instance = new Lazy<Temp>(() => new Temp());
private void OnProcessExit(Object sender, EventArgs e) {
// Release native resource if required:
// some resources e.g. files will be closed automatically,
// but some e.g. transactions should be closed (commit/rollback) manually
try {
...
}
finally {
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
}
}
private Temp() {
// create IDisposable objects which use native resources
// If you have to release some resouces on exit
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
}
public static Temp Instance {
get {
return instance.Value;
}
}
}
这篇关于我应该在单例上实现IDisposable吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!