Problems Using Statement Statement and WCF Client

I am wrapping all the code that calls WCF calls in a using statement in the thought that the object will be deleted correctly. When I search Google for the exception "The Http service located at .. too busy" I found this link http://msdn.microsoft.com/en-us/library/aa355056.aspx , which says that you should not use using instructions in typed proxies. Is this really so? I think I got a big code change (sigh). Does this issue only occur in typed proxies?

Code example:

private ServiceClient proxy; using(proxy = new ServiceClient("ConfigName", "http://serviceaddress//service.svc")){ string result = proxy.Method(); } 
+8
c # using-statement wcf
source share
3 answers

Kernel of the problem : at the end of your using block (which is usually a very good idea!), The WCF proxy will be deleted. However, during the removal of the WCF proxy server, exceptions may occur - and this can lead to incorrect application operation. Since this is done implicitly at the end of the using block, you cannot even see where the error occurs.

Typically, Microsoft recommends a pattern like this:

 private ServiceClient proxy; try { proxy = new ServiceClient("ConfigName", "http://serviceaddress//service.svc"); string result = proxy.Method(); proxy.Close(); } catch (CommunicationException e) { // possibly log error, possibly clean up proxy.Abort(); } catch (TimeoutException e) { // possibly log error, possibly clean up proxy.Abort(); } catch (Exception e) { // possibly log error, possibly clean up proxy.Abort(); throw; } 

You must explicitly call the proxy.Close() method and be prepared to handle any exceptions that may arise from this call.

+16
source share

Wrap the proxy operation and instantiation calls in a class that implements IDisposable . When disposing, check the status of the proxy server and clear the channel before closing.

 public void Dispose() { if (this.MyProxy != null && this.MyProxy.State == CommunicationState.Faulted) { this.MyProxy.Abort(); this.MyProxy.Close(); this.MyProxy = null; } // ...more tidyup conditions here } 
+2
source share

I like the approach from Eric's comment on this blog (which is similar to another article: http://redcango.blogspot.com/2009/11/using-using-statement-with-wcf-proxy.htm ):

“Personally, I like to create my own partial class for the client and override the Dispose () method. This allows me to use the“ block used, as usual. ”

 public partial class SomeWCFServiceClient : IDisposable { void IDisposable.Dispose() { if (this.State == CommunicationState.Faulted) { this.Abort(); } else { this.Close(); } } } 
+1
source share

All Articles