InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

The Problems with WCF and the Using Block

Posted by Jonathan Allen on Mar 05, 2009

Sections
Development,
Architecture & Design
Topics
Programming ,
Fault Tolerance ,
.NET
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
  1. Back to top

    Proposed solution by Microsoft

    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

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.

Interview: Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives

InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.

Beauty Is in the Eye of the Beholder

Alex Papadimoulis discusses ugly code, where it comes from, how to avoid it, and how to get rid of it.

Architecting Visa for Massive Scale and Continuous Innovation

John Davies examines Visa’s architecture and shows how enterprises have architected complex integrations incorporating Hadoop, memcached, Ruby on Rails, and others to deliver innovative solutions.

Max Protect: Scalability and Caching at ESPN.com

Sean Comerford unveils ESPN.com’s architecture, what components are used and why, and the current changes the website goes through.

The Seven Deadly Sins of Enterprise Agile Adoption

Are there repeated patterns of failure on Enterprise Agile Enablement efforts? Sanjiv and Arlen discuss Seven Deadly Sins to avoid when adopting Agile in an enterprise.

Questions for an Enterprise Architect

Erik Dörnenburg answers: What is Enterprise and Evolutionary Architecture?, discussing 4 issues: Turning strategy into execution, Ensuring conformance, Where do the architects sit? Buying or building?

Wrap Your SQL Head Around Riak MapReduce

Sean Cribbs explains what Map-Reduce and Riak are, why and how to use Map-Reduce with Riak, and how to convert SQL queries into their Map-Reduce equivalents.