We are using WCF service
on the client side we are planning to explicitly close the connection It seems there are more then one way of closing
Sample1: In the finally block of the WCF service consumption use
if (client.State == CommunicationState.Faulted)
{
client.Abort();
}
client.Close();
Since if the service is in fault state we will not be able to call close()
Sample2:
using(ClientProxy proxy = new ClientProxy())
{
//call your service methods
}
in sample2 i am not sure what will happen if the service is in fault state, will it throw error closing the connection?
You have all the necessary information at hand - the resulting Best Practice to use and properly close/abort all your WCF client proxies would be:
YourClientProxy clientProxy = new YourClientProxy();
try
{
.. use your service
clientProxy.Close();
}
catch(FaultException)
{
clientProxy.Abort();
}
catch(CommunicationException)
{
clientProxy.Abort();
}
catch (TimeoutException)
{
clientProxy.Abort();
}
Catching the FaultException handles all cases when the service responsded with an error condition (and thus your channel is in a faulted state), and CommunicationException will handle all other communication-related exceptions that can occur, like network connectivity dropping etc.
The approach with the using() block won't work, since if an exception happens at the end of the block, when the Dispose() method calls the Close() method on the client proxy, you have no way to catching and handling that.
The 2nd sample using the "using" block is incorrect. The using block ensures that the Dispose method is called on the proxy object. The Dispose method in turn calls the Close method which will (try to) connect to the service which will throw an exception when the communication state is faulted. So your feelings/hunch are absolutely right. It would be nice if the proxy Dispose method used the code from your first sample but it doesn't so don't use the using block :)
In Juval Lowy's Excellent Programming WCF book he recommends:
try
{
ClientProxy clientProxy = new ClientProxy();
clientProxy.SomeMethod();
clientProxy.Close();
}
catch
{
proxy.Abort();
}
Use sample 1
Here is a good article on why you should not use using:
http://msdn.microsoft.com/en-us/library/aa355056.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With