Pregunta

I'm a little confused about the best way to clean up a ServiceHost. I became aware of the issue in my code because of the CA1001 warning from the Visual Studio code analyzer suggesting I implement the IDisposable interface for my class.

I have read the discussions on IDisposable and am familiar with the typical use case, but find myself confused in this instance. What is the proper way to make sure that the ServiceHost is being disposed and possibly satisfy CA1001. Thanks.

My code looks something like the following:

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
        }
    }
}

¿Fue útil?

Solución

Your class should implement IDisposable. Based on the example from that MSDN page:

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);
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top