加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-14 04:16:27 所属栏目:Windows 来源:网络整理
导读:我遇到过这段代码: 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
我遇到过这段代码:
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()应该只用于允许尽早解除分配非托管资源.过程停止一毫秒之后就没有早期

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读