Search code examples
c#wcfidisposablewcf-4

Correct way to close WCF 4 channels effectively


I am using the following ways to close the WCF 4 channels. Is this right way to do it?

using (IService channel 
    = CustomChannelFactory<IService>.CreateConfigurationChannel())
{
    channel.Open();

    //do stuff
}// channels disposes off??

Solution

  • Although not strictly directed at the channel, you can do:

    ChannelFactory<IMyService> channelFactory = null;
    try
    {
        channelFactory =
            new ChannelFactory<IMyService>();
        channelFactory.Open();
    
        // Do work...
    
        channelFactory.Close();
    }
    catch (CommunicationException)
    {
        if (channelFactory != null)
        {
            channelFactory.Abort();
        }
    }
    catch (TimeoutException)
    {
        if (channelFactory != null)
        {
            channelFactory.Abort();
        }
    }
    catch (Exception)
    {
        if (channelFactory != null)
        {
            channelFactory.Abort();
        }
        throw;
    }