Peter Kjaer (SDL)

November 30, 2011

Core Service clients and the “using” statement

Filed under: Core Service — Tags: , , , , , — Peter Kjaer @ 11:38 AM

I learned something new this week: although WCF clients implement IDisposable, you should not put them in a “using” statement.


See the following MSDN article: Avoiding Problems with the Using Statement

Sure, it will close the connection when you’re done with it. But if the connection is in a faulted state, Dispose will actually throw an exception (despite this going against best practices).


The MSDN article suggests that you catch specific exceptions and then call Abort instead of Close.

I think a finally block is a better place:

try
{
   [...]
}
finally
{
   if (client != null)
   {
      if (client.State == CommunicationState.Faulted)
      {
         client.Abort();
      }
      else
      {
         client.Close();
      }
   }
}


Advertisements

1 Comment »

  1. […] Peter Kjaer (SDL) I think a finally block is a better place: […]

    Pingback by SDL Tridion WCM by rhertel - Pearltrees — December 7, 2011 @ 12:50 AM


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: