我对清理 ServiceHost 的最佳方法有些困惑。由于 Visual Studio 代码分析器的 CA1001 警告建议我为我的类实现 IDisposable 接口(interface),因此我意识到了我的代码中的问题。

我已阅读有关 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
        }
    }
}

最佳答案

你的类应该实现 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);
    }
}

关于c# - 正确清理 System.ServiceModel.ServiceHost,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15642628/

10-11 07:27