【问题标题】:Correct place to dispose of WebApp.Start instance in a Window service?在 Window 服务中处理 WebApp.Start 实例的正确位置?
【发布时间】:2016-02-22 13:23:14
【问题描述】:

我正在编写一个 Windows 服务,它将自托管 OWIN WebApi Web 服务。要启动 Web 服务,位置非常明显;在ServiceBase-extending 类的OnStart 方法中:

private IDisposable _webApiDataConnectionHost;

protected override void OnStart(string[] args) {
    _webApiDataConnectionHost = WebApp.Start<OwinWebStartup>("...");
}

但是,我不确定在哪里处理网络应用程序。在this example project 中,他们在OnStop 方法中处理它:

protected override void OnStop()
{
    if(_server != null)
    {
        _server.Dispose();
    }
    base.OnStop();
}

但是鉴于这是一个IDisposable,在服务的Dispose 方法的覆盖中处理它不是正确的吗?类似于以下内容:

protected override void Dispose(bool disposing) {
    if (disposing) {
        if (components != null) { components.Dispose(); }

        // Dispose of our web app if it exists...
        if (_webApiDataConnectionHost != null) {
            _webApiDataConnectionHost.Dispose();
        }
    }

    base.Dispose(disposing);
}

哪个是处理网络应用程序的合适位置?

【问题讨论】:

    标签: c# .net asp.net-web-api windows-services owin


    【解决方案1】:

    我通常设置任何服务的方式是实现 IDisposable 接口并从 OnStop 调用 Dispose 方法。我的 OnStop 通常与我的 OnPause 相同,但需要额外调用 Dispose。可以看msdnhere的推荐。

    【讨论】:

      【解决方案2】:
      • IDisposable 保证垃圾回收,迟早
        • 如果您不致电 Dispose(),则收集可能会在稍后不确定地发生。
      • 由于它是一项服务,您知道您希望该服务何时停止,因此您自己致电 Dispose() 是很有意义的,在 OnStop() 中也是如此。
      • 另外,您将只运行它的一个实例 - 所以使用单例设计模式。如果多个线程将访问单例实例,请实施线程安全模式。

      如果我理解正确,您在服务覆盖Dispose() 中编写的代码只是确保当实例被垃圾收集时,所有 资源将被释放。使用该方法,您可以确保无论何时发生 dispose 都会正确发生。您仍然需要在 OnStop() 中调用此覆盖方法。


      * Do I need to dispose a web service reference in ASP.NET?

      * Remarks on Disposing ServiceBase - 在 Kent Cooper 的回答中也有链接。

      【讨论】:

        猜你喜欢
        • 2019-11-26
        • 1970-01-01
        • 2018-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多