4

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

4

1 に答える 1

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);
    }
}
于 2013-03-26T17:39:17.027 に答える