Windows Communication Foundation clients and IDisposable

If you are using a WCF client make sure you either Close() or Dispose() the client when you are done. I failed to do so and got bitten by a big memory leak [:(] I was using a NetMsmqBinding and forgot to close the client when done. By itself the code worked just fine, no leaks or nothing. But then the same piece of code got called from inside another NetMsmqBinding server during the reception of a message and it generated a memory leak big time. Of course I should have Disposed() the client but the IDispose implementation is private so without casting it doesn’t show up making it easy to forget, the Close() was public so no excuses there [:)]. The best solution is to use the Using keyword (using in C#) and it will make sure Dispose() is called if it exists.

 

Another thing that would have saved the day was if the ClientBase(Of TChannel As Class) implemented the IDisposable design pattern instead of just implementing the IDisposable interface. Using the design pattern ensures that the resources are disposed regardless of Dispose() being called. See http://msdn2.microsoft.com/en-us/library/fs2xkftw.aspx for more information about the IDisposable design pattern.

 

Enjoy!

 


One thought on “Windows Communication Foundation clients and IDisposable

  1. This bit me recently, too, but it turns out Close() — Dispose() calls Close() — must be called in a try/catch block because if the server returns a Fault message the client object must Abort(). It cannot be disposed!! This is so stupid and makes me so sick to my stomach that Microsoft implemented IDispose with it throwing exceptions, but that’s the painful truth.

    So, the “best” way to deal with the client is not ..

    using (ClientType client = new ClientType())
    {
    client.MyMethod();
    }

    .. but rather ..

    ClientType client = new ClientType();
    client.MyMethod();
    try
    {
    client.Close();
    }
    catch
    {
    client.Abort();
    }

    Fun, huh? Not ..

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>