InfoQ

News

The Problems with WCF and the Using Block

Posted by Jonathan Allen on Mar 05, 2009

Community
.NET
Topics
Fault Tolerance ,
Programming
Tags
WCF

WCF Clients cannot be used inside a Using block because they may unexpectedly throw an exception. And even if you catch the exception, it is possible that a connection will be left open. We look into the history of this issue and some proposed workarounds.

The corner-stones of resource management in .NET are IDisposable and the Using block. Aside from CLR objects, the lifespan of everything in the .NET world is managed using these tools. So one has to wonder how Microsoft managed to fail so miserably with the WCF framework.

The first problem with WCF clients is that the Close/Dispose method can throw an exception. In a clear violation of the Framework Design Guidelines and the IDisposable contract, this makes the Dispose method unsafe to call from a Finally block.

Even worse, there is a chance that the Close/Dispose method can leave the connection open if Abort isn’t called. If too many are left open this can leave to performance problems or application instability.

In a newsgroup thread dating back to 2006, Brian McNamara gives us the back-story on the design flaw.

ICommunicationObject (from which ServiceHost, ClientBase, IChannel, IChannelFactory, and IChannelListener ultimately derive) has always had two methods for shutting down the object: (a) Close, and (b) Abort. The semantics are that if you want to shutdown gracefully, call Close otherwise to shutdown ungracefully you call Abort.

As a consequence, Close() takes a Timeout and has an async version (since it can block), and also Close() can throw Exceptions. Documented Exceptions out of Close are CommunicationException (of which CommunicationObjectFaultedException is a subclass), and TimeoutException.

Abort() conversely is not supposed to block (or throw any expected exceptions), and therefore doesn’t have a timeout or an async version.

These two concepts have held from the inception of Indigo through today. So far, so good.

In its original incarnation, ICommunicationObject : IDisposable. As a marker interface, we thought it would be useful to notify users that the should eagerly release this object if possible. This is where the problems begin.

Until Beta 1, we had Dispose() == Abort(). Part of the reasoning was that Dispose() should do the minimum necessary to clean up. This was possibly our #1 complaint in Beta 1. Users would put their channel in a using() block, and any cached messages waiting to be flushed would get dropped on the floor. Transactions wouldn’t get committed, sessions would get ACKed, etc.

Because of this feedback, in Beta 2 we changed our behavior to have Dispose() ~= Close(). We knew that throwing causes issues (some of which are noted on this thread), so we made Dispose try to be “smart”. That is, if we were not in the Opened state, we would under the covers call Abort(). This has its own set of issues, the topmost being that you can’t reason about the system from a reliability perspective. Dispose can still throw, but it won’t _always_ notify you that something went wrong. Ultimately we made the decision that we needed to remove IDisposable from ICommunicationObject. After much debate, IDisposable was left on ServiceHost and ClientBase, the theory being that for many users, it’s ok if Dispose throws, they still prefer the convenience of using(), and the marker that it should be eagerly cleaned up. You can argue (and some of us did) that we should have removed it from those two classes as well, but for good or for ill we have landed where we have. It’s an area where you will never get full agreement, so we need to espouse best practices in our SDK samples, which is the try{Close}/catch{Abort} paradigm.

Workarounds

Steve Smith has proposed a CloseConnection extension method. This method, called from a Finally block instead of Close, would encapsulate the Close/Abort logic.

A newsgroup poster going by bog1978 suggests using C#’s lambda support to create your own Using-like construct. This method takes a new client object and an anonymous method that holds the same code a normal using block would contain.

Finally there is the WCF Service Proxy Helper class from Erwyn Van Der Meer. Users create this instead of the normal proxy class and it will do the correct thing when closing the connection. When created, it will automatically construct the actual proxy, exposing it via a read-only property.

Proposed solution by Microsoft by Federico Boerr Posted Mar 5, 2009 6:17 PM
  1. Back to top

    Proposed solution by Microsoft

    Mar 5, 2009 6:17 PM by Federico Boerr

    Here's the pattern that Microsoft proposes: msdn.microsoft.com/en-us/library/ms733912.aspx.

    In a few words, don't use a WCF client in a using block.

Educational Content

Brian Marick on 4 Challenges and 5 Guiding Values of Agile Software Development

Brian Marick takes us through a quick tour of the most important values and challenges to adopting Agile successfully (they aren't the typical challenges and values we hear in the community).

Are You a Software Architect?

The line between development and architecture is tricky. Does it exist at all? Is an ivory tower actually needed? There's a balance in the middle, but how do you move from developer to architect?

Agile – A Way of Life and Pragmatic Use of Authority

The word 'authority' sometimes produces an allergic response in hard-line agilists. Freedom and authority – both are bad if misused and both are good if used in right spirit for a noble cause.

Getting Started with Grails, Second Edition

"Getting Started with Grails" brings you up to speed on this modern web framework. Companies as varied as LinkedIn, Wired, and Taco Bell are all using Grails. Are you ready to get started as well?

Using ITIL V3 as a Foundation for SOA Governance

Those familiar with only ITIL V2 often scoff at the thought that ITIL could serve as a governance framework for SOA. With ITIL V3, the focus of the framework shifted towards service-orientation.

Adrian Colyer on AspectJ, tc Server and dm Server

SpringSource CTO Adrian Colyer discusses AspectJ, SpringSource's dm Server and tc Server products, OSGi and Scrum.

Adam Wiggins on Heroku

Heroku's Adam Wiggins talks about Rails, Background Jobs, Add-Ons, Ruby, and how Heroku manages to work around Ruby's inefficiencies using Erlang and other languages.

SOA as an Architectural Pattern: Best Practices in Software Architecture

For Grady Booch the foundation of a good architecture is patterns, SOA being just one of many patterns. In this Second Life presentation, Booch attempts to bring more clarity on what architecture is.