我遇到过这段代码:
public class ServiceLauncher2 : ServiceBase,Idisposable
然后这个:
/// <summary> /// disposes the controllers /// </summary> // This is declared new as opposed to override because the base class has to be able to // call its own dispose(bool) method and not this one. We Could just as easily name // this method something different,but keeping it dispose is just as valid. public new void dispose() { foreach (var mgr in _threadManagers) mgr.dispose(); base.dispose(); }
我之前从未在Windows服务实现中看到过这种情况.通常只会覆盖OnStop / OnStart.这是不好的做法吗?
让我们算一下这是不好的做法:
>新关键字是格栅,它告诉编译器关闭代码中的潜在问题.一个真实的,使用这个类的代码很容易最终调用ServiceBase.dispose(). ServiceBase实现了一次性模式,正确的方法是覆盖受保护的dispose(bool)方法
> dispose()方法在后面留下一个_threadManagers集合对象,它只包含死对象.这使得这个系列也像死亡一样死了,之后迭代它是没有意义的.它本应该被清空
>唯一可以调用此dispose()方法的是服务终止.无法在OnStop()中执行此操作,它还处理了ServiceBase.在终结器运行之前处理“控制器”一微秒并且该过程终止是没有意义的. dispose()应该只用于允许尽早解除分配非托管资源.过程停止一毫秒之后就没有早期
这段代码毫无意义.不要使用它.