Monday, March 22, 2010

Closing A WCF Proxy

MSDN has a whole page on why you shouldn't use a using statement to manage the lifetime of a WCF service proxy. Succinctly, closing a WCF proxy actually makes a call to the server to tell it to "hang up", and this action can fail if the server is unreachable. Disposing a WCF proxy closes it. If your proxy gets disposed and closed at the end of a using block and the call to the server fails, the closing brace of your using statement will throw an exception. What's more, if you threw an exception inside the using statement, it disappears, because the failing close/dispose threw its own exception afterwards.

The page gives an example of how to properly handle closing a proxy, but like many MSDN pages, a better answer is given in the Community Content at the end of the page: don't use the using statement, wrap your proxy work in a try, and in the finally block, have another try/catch that tries to close the proxy and aborts instead if the close fails.

finally
{
   try
   {
      client.Close();
   }
   catch
   {
      client.Abort();
   }
}
Don't forget to catch CommunicationExceptions and TimeoutExceptions before catching any others!

No comments: