Closing WCF connection

前端 未结 4 1280
南方客
南方客 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: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.

提交回复
热议问题