Windows服务实现IDisposable - 这是不好的做法?

Jon*_*nor 8 windows c#-4.0

我遇到过这段代码:

public class ServiceLauncher2 : ServiceBase, IDisposable
Run Code Online (Sandbox Code Playgroud)

然后这个:

        /// <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();
        }
Run Code Online (Sandbox Code Playgroud)

我之前从未在Windows服务实现中看到过这种情况.通常只会覆盖OnStop/OnStart.这是不好的做法吗?

Han*_*ant 12

让我们算一下这是不好的做法:

  • 新的关键字光栅,它告诉编译器闭嘴代码中的一个潜在的问题.一个真实的,使用这个类的代码很容易最终调用ServiceBase.Dispose().ServiceBase实现了一次性模式,正确的方法是覆盖受保护的Dispose(bool)方法

  • Dispose()方法在后面留下一个_threadManagers集合对象,它只包含死对象.这使得该集合也成为一个死亡之后,之后迭代它是毫无意义的.它本应该被清空

  • 唯一一次可以调用Dispose()方法是在服务终止时.无法在OnStop()中执行此操作,它还处理了ServiceBase.在终结器运行之前处理"控制器"一微秒并且该过程终止是没有意义的.Dispose()应该只用于允许尽早解除分配非托管资源.过程停止一毫秒之后就没有早期

这段代码毫无意义.不要使用它.