TIP: Closing your WCF Connections properly

In a previous tip, you looked at how you could use ChannelFactory or Proxy Classes to talk to a WCF service. Now you can have a look at how to properly close of these connections.

If you've used Visual Studio to generate a WCF proxy class for one of your WCF services, go on and have a look at it now. In it, have a look at the generated client class:

public partial class StockServiceClient : System.ServiceModel.ClientBase<StockService.IStockService>, StockService.IStockService {
...

The client that you use in your main code inherits from ClientBase<>. Looking at ClientBase on MSDN, you see that it implements IDisposable. As with most other classes implementing IDisposable, it is tempting to use the C# using statement for your WCF clients.

//It's tempting, but don't do this:
using(StockService.StockServiceClient client = new StockService.StockServiceClient(
              "StockBasicHttpEndpoint", stockServiceUrl))
{
client.GetStockIdByName("MSFT");
}

And as you know, the using block will automatically call client.Dispose() when it's done. There's a problem with it though — with ClientBase, the Dispose() method makes a call to Close(). When the ClientBase's Close() method is called, a web service call actually goes out to the WCF service, informing it that the connection session is no longer required. This appears counter-intuitive, but it was done by design. The problem with this mechanism is that when the Close() method is called, an exception can be thrown. After all, it involves yet another network call to a web service. It's for this reason that the using statement isn't recommended with WCF clients.

Instead, you should attempt to Close() it in a try-catch block, with the catch block performing an Abort()

//Call your web service as usual.
StockService.StockServiceClient client = new StockService.StockServiceClient(
              "StockBasicHttpEndpoint", stockServiceUrl);

string StockId = client.GetStockIdByName("MSFT");

//Done with the service, let's close it.
try
{
   if (client.State != System.ServiceModel.CommunicationState.Faulted)
   {
      client.Close();
   }
}
catch (Exception ex)
{
   client.Abort();
}

The same thing applies to your ChannelFactory, if you use one — and the code to close it is exactly the same.
//Create channel from factory
ChannelFactory channel =
   new ChannelFactory<IService1>("bindingName");
IService1 client = channel.CreateChannel();

client.DoWork();

//Done with the service, let's close it.
try
{
   if (client.State != System.ServiceModel.CommunicationState.Faulted)
   {
      client.Close();
   }
}
catch (Exception ex)
{
   client.Abort();
}

So the points made here, very briefly, are

  • Don't use 'using' with your WCF client classes
  • .Close() the client in a try-catch block and .Abort() it if an exception occurs.


About the Author

SM Altaf

Mendhak is a web developer and a Microsoft MVP who works with ASP.NET and PHP among the usual array[] of web technologies. He is also rumored to be a three eyed frog, but the evidence is lacking. He can be contacted via his website, www.mendhak.com.


Comments

  • знакомства анкеты участников

    Posted by griegosic on 07/01/2013 05:32am

    Стресс, заключил он и разразился заковыристой латынью. Наверняка Гильдия не оставит ее в покое. Арамис взял его из рук коменданта, не торопясь разорвал на четыре части, поднес их к лампе и сжег. А этот сукин сын не соглашался говорить, куда он ее дел. Отмахать столько по пустыне, чтобы утонуть или поджариться от молнии, было бы совсем обидно. [url=http://poznakomtes.ded-of.ru.com/dating21-09-2012.php]знакомства г.югорск[/url] А позади всех шли еще пятнадцать воинов из Преданной Тысячи. Думаю, родись мамулечка двадцать лет назад, она бы сейчас гуляла, наплевав на работу. Самая безобидная с виду вещь может таить в себе огромную силу, заметил Гонинан. Ты выглядишь как-то странно, - Тереза пристально вглядывалась в его лицо. Рано или поздно ему встретится молодая девушка или ребенок — и что тогда? [url=http://znakomstva-tabor.ded-of.ru.com/dating10-10-2012.php]бесплатное знакомство с транссексуалами[/url] Отряд за воротами встретил предводителя радостными криками. Разумом я уже почти согласна с ним, но если говорить о чувстве — я все еще чувствую, как прекрасны некоторые картины, которые он ругает.

    Reply
  • Cheap Oakley Whisker online store

    Posted by ugapewphl on 06/29/2013 05:57am

    Fake oAkLeys ,Regardless of product, provided that careful after years of experience in design, production and market demand will probably be loved from the public. Can not be denied the truth is that this market equipment and items for ladies is far greater than men's accessories market Japanese products. Fake ray bans ,Oakley Eyewear lenses in bright light finest in sunny conditions, all of the lens use a truer color perception. In fact, you could end up more eye-catching casing an incredible selection of sunglasses, including an amazing beveled plastic frames, ebony frame of yellow metal, old watches, along with your favorite color. OAklEY EyepAtch ,Regardless if you are what sort of person, or a two of sunglasses, it really is for you personally. These sunglasses are actually created to meet the needs coming from all personal taste. Oakley sunglasses lenses are safe, no pressure, may get a new optical pause, therefore you have to be truthful, accurate vision premium clarity. Hitting the ground with your skin layer, nose pad special high-energy minerals thetemperature reached 32 degrees, or not accountable for the special energy and negative ions, to get the antioxidant, and gradually the role of cell activity, and promote head circulation, thus effectively relieve eye fatigue . Brought up regarding how to determine the Oakley sun's shadow, exactly why do not we back to re-examine why young adults could do with the Oakley shades. The reason why is because they could increase security on the eyes. You can utilize in biochemistry Labrador, and also wood processing. They might be doing work in the snow track and field, along with swimming. Oakley Holbrooke cheap sunglasses online to draw a great number of customers, create an increasing number of boys and females has a state-of-the-art glasses gloss. The integration of science and art Oakley won a lot more than 600 patents worldwide. Today, Jannard's brand has become a prominent symbol of success. Oakley hydrophobic, oleophobic technology, high-performance coatings, water slide out, to hold up your eyes clear, and overcome the stain from skin oils and lotions. Once the shop offers his / her goods by the enterprises or their real supplier of wholesale prices, regional, that may reduce transportation costs, besides assist you to personalize your romantic relationships with distributors. If you want wholesale sunglasses online purchase is a great choice. This is a easy way to compare different sunglasses provide them with the cost of their articles, their make of wholesalers and retailers.

    Reply
  • I don't think so either!

    Posted by Mark on 04/17/2012 07:19am

    You are better off aborting the object in the 'Finally' part of the try-ctach. In your example you won't be able to abort unless exception is thrown. What if no exception is thrown but the transaction lasts forever? You then have to realy on yout timeout quota, which effectively (in the case of a large app) may end up in multiple sessions lingering and waiting to be disposed off. Please remove this post - it is nto right and may be confusing for some readers. Regards.

    Reply
  • No, I don't think so.

    Posted by JerryNixon on 03/09/2011 03:12pm

    1. With your TIP the method call (cal named it DoWork()) may fail, causing the flow to exit the method and bypass the possibility of the Abort() call in your catch { client.Abort(); }. 2. WIth your TIP the method call may pass, but the state may be faulted, but Abort() cannot be called because an exception is required. It seems to me that you should: 1. Move the method call into your try { } block. 2. Remove the (State != Faulted) if statement. Are you sure about your suggestion here?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • It's time high-level executives and IT compliance officers recognize and acknowledge the danger of malicious insiders, an increased attack surface and the potential for breaches caused by employee error or negligence. See why there is extra emphasis on insider threats.

  • Live Event Date: April 29, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Leveraging Flash storage to accelerate an Oracle Real Application Clusters (RAC) environment is one of today's hottest technology topics. Oracle databases require guaranteed levels of storage performance and high availability of data. Until recently, Oracle RAC could only use Flash storage for SmartFlash Cache, which addresses some performance improvements, but limits the benefits that can be gained from a shared Flash infrastructure. Enter …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds