matthewlynch.net Musings on programming, electronics, and other such things.

16Sep/100

WCF and Using()

Encountered an interesting problem recently, while building a WCF solution.

My code ran fine on my development machines, but when I deployed the solution to production I started receiving a timeout exception; specifically a System.ServiceModel.CommunicationException.

This was strange because the supposed timeout was happening instantly on a system with a timeout threshold of 10 seconds...

After some head scratching and searching, I found the problem: If you use a WCF service client with the Using() statement, any exception that occurs during the call to Close() - implicitly done at the end of the using block - will mask exceptions that occur within the using statement.

To make matters worse, the call to Close() will almost always throw a System.ServiceModel.CommunicationException if the service client throws an exception higher up the chain.

The solution is fairly simple: use a try-catch-finally pattern instead.

In my case the actual exception was a System.ServiceModel.Security.MessageSecurityException, which was easily fixed with a configuration change.

Filed under: .NET, C#, WCF No Comments