Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing WCF connection

Tags:

wcf

connection

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?

like image 801
Balaji Avatar asked Sep 09 '09 14:09

Balaji


4 Answers

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.

like image 199
marc_s Avatar answered Oct 20 '22 15:10

marc_s


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 :)

like image 40
olle Avatar answered Oct 20 '22 15:10

olle


In Juval Lowy's Excellent Programming WCF book he recommends:

try 
{
    ClientProxy clientProxy = new ClientProxy();
    clientProxy.SomeMethod();
    clientProxy.Close();
}
catch
{
    proxy.Abort();
}
like image 4
RichardOD Avatar answered Oct 20 '22 14:10

RichardOD


Use sample 1

Here is a good article on why you should not use using:

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

like image 2
Shiraz Bhaiji Avatar answered Oct 20 '22 14:10

Shiraz Bhaiji