Correct way to close WCF 4 channels effectively

怎甘沉沦 提交于 2019-12-21 03:46:11

问题


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??

回答1:


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;
}



回答2:


That used to be the commonly accepted way to release WCF client proxies in the "early" days of WCF.

However things have since changed. It turned out that the implementation of IClientChannel<T>.Dispose() simply invokes the IClientChannel<T>.Close() method, which may throw an exception under some circumstances, such as when the underlying channel isn't open or can't be closed in a timely fashion.

Therefore it's not a good idea to invoke Close() within a catch block since that may leave behind some unreleased resources in case of an exception.

The new recommended way is to invoke IClientChannel<T>.Abort() within the catch block instead, in case Close() would fail. Here's an example:

try
{
    channel.DoSomething();
    channel.Close();
}
catch
{
    channel.Abort();
    throw;
}

Update:

Here's a reference to an MSDN article that describes this recommendation.



来源:https://stackoverflow.com/questions/9061923/correct-way-to-close-wcf-4-channels-effectively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!