Friday, 18 January 2008

If you work with WCF, you should never forget to Close or Dispose your proxies when you do not need them anymore, because otherwise you might keep unmanaged resources (ports, channels, whatever) allocated. This does not sound too interesting or unusual yet, as we have all come across disposable objects before. In a particular project, I used “using statements” as usual, since the proxies implemented the IDisposable interface.

But the following issue surprised me in my current project: you should NOT use the “using” statement to ensure the proxy is disposed! For the details, have a look at this article. In a nutshell, the reason is that the Close method tries to close the communication in a “nice way”, and this sometimes requires further communication or other complex activities. Unfortunately, this operation can throw exceptions, and it does not matter whether you called Dispose or Close to initiate the closing operation.

If you think about what the using statement means (the Dispose is executed in the “finally”), it is only a good pattern when Dispose works “safely”, so it does not throw exceptions when you want to get rid of the object already anyway. If there is a chance of an exception occurring during Dispose, you might run into trouble with this approach, e.g. a “real” exception from the body of the using statement may get hidden by an uninteresting exception that just informs you that you cannot close the communication nicely.

In my case, I was constantly receiving the following error:
System.ServiceModel.CommunicationObjectFaultedException: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.
In reality, I had a problem with the installed certificates used for message encoding, but the specific exception was hidden by this error thrown from the Dispose call of the using statement. I had to get rid of the using statement and use a try-catch approach first to reveal the actual problem.

I hope this spares you some time and hair.

Posted by TZ.

WCF
Friday, 18 January 2008 22:31:47 (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  |  Related posts:
Web Service proxies and shared types

Comments are closed.