Closing WCF connection

前端 未结 4 1271
南方客
南方客 2020-12-05 10:23

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 t

相关标签:
4条回答
  • 2020-12-05 10:39

    Use sample 1

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

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

    0 讨论(0)
  • 2020-12-05 10:41

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

    try 
    {
        ClientProxy clientProxy = new ClientProxy();
        clientProxy.SomeMethod();
        clientProxy.Close();
    }
    catch
    {
        proxy.Abort();
    }
    
    0 讨论(0)
  • 2020-12-05 10:48

    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.

    0 讨论(0)
  • 2020-12-05 10:52

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

    0 讨论(0)
提交回复
热议问题