Click here to Skip to main content
15,393,377 members
Articles / General Programming / Performance
Posted 17 May 2011

Tagged as


39 bookmarked

Do not use "using" for WCF Clients

Rate me:
Please Sign up or sign in to vote.
4.83/5 (26 votes)
17 May 2011CPOL1 min read
Traditional using() block disposes WCF clients incorrectly when there's a communication exception, eg dropping network connection. It raises exception during the dispose and thus the resources held by the WCF client aren't released properly. After some time, you end up with memory leaks.
You know that any IDisposable object must be disposed using using. So, you have been using using to wrap WCF service’s ChannelFactory and Clients like this:
using(var client = new SomeClient()) {
Or, if you are doing it the hard and slow way (without really knowing why), then:
using(var factory = new ChannelFactory<ISomeService>()) {
var channel= factory.CreateChannel();
That’s what we have all learnt in school right? We have learnt it wrong!
When there’s a network related error or the connection is broken, or the call is timed out before Dispose is called by the using keyword, then it results in the following exception when the using keyword tries to dispose the channel:
failed: System.ServiceModel.CommunicationObjectFaultedException : 
The communication object, System.ServiceModel.Channels.ServiceChannel, 
cannot be used for communication because it is in the Faulted state.
    Server stack trace: 
    at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)
    Exception rethrown at [0]: 
    at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
    at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
    at System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
    at System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
    at System.ServiceModel.ClientBase`1.Close()
    at System.ServiceModel.ClientBase`1.System.IDisposable.Dispose()

There are various reasons for which the underlying connection can be at broken state before the using block is completed and the .Dispose() is called. Common problems like network connection dropping, IIS doing an app pool recycle at that moment, some proxy sitting between you and the service dropping the connection for various reasons and so on. The point is, it might seem like a corner case, but it’s a likely corner case. If you are building a highly available client, you need to treat this properly before you go-live.
So, do NOT use using on WCF Channel/Client/ChannelFactory. Instead you need to use an alternative. Here’s what you can do:
First create an extension method.
public static class WcfExtensions
    public static void Using<T>(this T client, Action<T> work)
        where T : ICommunicationObject
        catch (CommunicationException e)
        catch (TimeoutException e)
        catch (Exception e)

Then use this instead of the using keyword:
new SomeClient().Using(channel => {
    channel.Login(username, password);

Or if you are using ChannelFactory then:
new ChannelFactory<ISomeService>().Using(channel => {    
    channel.Login(username, password);



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Comments and Discussions

GeneralMy vote of 5 Pin
Member 1350234030-Nov-21 6:20
MemberMember 1350234030-Nov-21 6:20 
QuestionIssue on ChannelFactory code Pin
Francois M5-Apr-17 7:57
MemberFrancois M5-Apr-17 7:57 
QuestionMicrosoft give a pretty good explanation why using statements should be avoided Pin
Matt-minke20-Jan-16 8:44
MemberMatt-minke20-Jan-16 8:44 
GeneralThat makes it too simple doesn't it. Pin
stixoffire17-Nov-15 10:16
Memberstixoffire17-Nov-15 10:16 
GeneralThanks Pin
par4dise21-Jul-14 6:05
Memberpar4dise21-Jul-14 6:05 
GeneralMy vote of 5 Pin
Srinivass Rayabandi23-Jan-13 1:40
MemberSrinivass Rayabandi23-Jan-13 1:40 
BugMy WCF Service hosted on iis is responding slow on client machine. Pin
Prem Gangwar15-Jun-12 7:34
MemberPrem Gangwar15-Jun-12 7:34 
QuestionWhat should be extension if operation returns value? Pin
Michael Freidgeim29-Jan-12 13:40
MemberMichael Freidgeim29-Jan-12 13:40 
AnswerRe: What should be extension if operation returns value? PinPopular
STRICQ19-Apr-12 11:01
MemberSTRICQ19-Apr-12 11:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.