正确清理System.ServiceModel.ServiceHost

den*_*ver 4 c# wcf idisposable servicehost

我对清理ServiceHost的最佳方法感到困惑.我在代码中发现了问题,因为Visual Studio代码分析器发出了CA1001警告,建议我为我的类实现IDisposable接口.

我已经阅读了关于IDisposable的讨论并熟悉了典型的用例,但在这个例子中发现自己很困惑.确保ServiceHost正在处理并可能满足CA1001的正确方法是什么.谢谢.

我的代码如下所示:

public class MyClass
{
    private ServiceHost host = null;

    public void StartListening(...)
    {
        // make sure we are not already listening for connections
        if (host != null && host.State != CommunicationState.Closed)
            StopListening();

        // create service host instance
        host = new ServiceHostWithData(typeof(ServiceHandler), address);

        // do a bunch of configuration stuff on the host

        host.Open();
    }

    public void StopListening()
    {
        // if we are not closed
        if ((host != null) && (host.State != CommunicationState.Closed))
        {
            host.Close();
            host = null;
        }
        else // we are null or closed
        {
            host = null; // if it isn't null, and it is already closed, then we set it to null
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

The*_*man 5

你的类应该实现IDisposable.基于该MSDN页面的示例:

public class MyClass : IDisposable
{
    private bool disposed = false;
    private ServiceHost host = null;

    public void StartListening(...)
    {
        // ....
    }

    public void StopListening()
    {
        // ...
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    { 
        if(!this.disposed)
        {
            if(disposing)
            {
                this.StopListening();
            }

            disposed = true;
        }
    }

    ~MyClass()
    {
        Dispose(false);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 关闭和处置基本上是相同的(看到答案在这里:http://stackoverflow.com/questions/4964161/wcf-how-to-stop-myservicehost-close-from-disposing-of-myservicehost-object),所以你也可以使用.请注意,ServiceHost上的close/dispose可能会抛出异常(!),因此您可能希望尝试/捕获该块,特别是如果您在MyClass Dispose函数中执行其他工作. (2认同)