Wednesday, October 22, 2014

Calling a WCF client proxy properly


There is a lot of discussion on how to use the WCF client proxy correctly. This is one use case where you do NOT want to use the elegant using statement, whether you are instantiating the client proxy directly or creating a service factory to create the WCF channel. In other words, don't do either of these:

using ( var client = new WcfClientProxy())
{
    .........
    .........
}

Or

using (var factory = new ChannelFactory<ISomeService>())
{
     var channel = factory.CreateChannel()
     ..........
     ..........
}


This is because the channel could have faulted ( a timeout, a connection fault etc) before dispose can be called with the using statement (the last } is where dispose is called).

The accepted best practice is to

  • wrap the call to the WCF Service using a try catch block
  • call close on the proxy at the end of the call in the try block
  • call abort (immediately calls close) at the end of each catch statement

Not doing so could leave a lot of open and non-usable channels and connections on your Server serving the WCF requests, thereby degrading performance significantly.

SO Reference
http://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue

MSDN article
http://msdn.microsoft.com/en-us/library/aa355056.aspx

And here's an interesting blog on it
http://adamprescott.net/2013/07/18/wcf-client-closal-disposal/