我有一个 Windows 服务,其中包含一个单例,该单例又使用一些记录器、消息队列侦听器等。这些类实现了IDisposable
。我应该实施IDisposable
在单例本身中还是做其他事情来确保服务停止/崩溃后,本机资源一切正常?
单例是这样实现的:
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
provokes开发商至Dispose(单个)实例:
using(var temp = Temp.Instance) {
...
}
这导致(可能)crash in 应用程序的其他部分(由于单Temp
实例已被处置):
Temp.Instance.SomeFucntion(); // <- possible fail, since Temp.Instanceis disposed
在极少数情况下,如果您必须释放获得的一些资源,我会使用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;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)