我正在使用以下方式关闭WCF 4通道。这是正确的做法吗?
using (IService channel
= CustomChannelFactory<IService>.CreateConfigurationChannel())
{
channel.Open();
//do stuff
}// channels disposes off??
我正在使用以下方式关闭WCF 4通道。这是正确的做法吗?
using (IService channel
= CustomChannelFactory<IService>.CreateConfigurationChannel())
{
channel.Open();
//do stuff
}// channels disposes off??
这曾经是WCF“早期”释放客户端代理常用的方法。
然而,事情已经有所改变。原来IClientChannel<T>.Dispose()的实现只会调用IClientChannel<T>.Close()方法,在某些情况下,例如底层通道未打开或无法及时关闭等情况下,这可能会引发异常。
因此,在catch
块中调用Close()
不是一个好主意,因为在出现异常的情况下,这可能会留下一些未释放的资源。
现在推荐的新方法是,在catch
块中调用IClientChannel<T>.Abort(),以防止Close()
操作失败。以下是一个示例:
try
{
channel.DoSomething();
channel.Close();
}
catch
{
channel.Abort();
throw;
}
更新:
这里提供了一篇 MSDN 文章的参考,该文章描述了该建议。
虽然不是专门针对渠道的,但你可以执行以下操作:
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;
}