gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:03:27 24 4
gpt4 key购买 nike

我遇到过这段代码:

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 被覆盖。这是不好的做法吗?

最佳答案

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

  • new 关键字很烦人,它告诉编译器对代码中的潜在问题闭嘴。一个真实的,使用这个类的代码很容易最终调用 ServiceBase.Dispose() 而不是。 ServiceBase实现了disposable模式,正确的做法是重写protected的Dispose(bool)方法

  • Dispose() 方法留下一个 _threadManagers 集合对象,它只包含死对象。这也使该系列像门钉一样死了,之后对其进行迭代毫无意义。应该是清空了

  • 只能在服务终止时调用此 Dispose() 方法。在 OnStop() 中做不到,它也处理了 ServiceBase。在终结器运行和进程终止之前一微秒处理“ Controller ”是没有意义的。 Dispose() 应该只用于允许非托管资源尽早解除分配。进程停止一毫秒后没有早

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

关于Windows 服务实现 IDisposable - 这是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15369715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com