有效关闭WCF 4通道的正确方法
本文关键字:方法 通道 WCF 有效 | 更新日期: 2023-09-27 18:21:47
我正在使用以下方法关闭WCF 4通道。这样做对吗?
using (IService channel
= CustomChannelFactory<IService>.CreateConfigurationChannel())
{
channel.Open();
//do stuff
}// channels disposes off??
在WCF的"早期",曾经是发布WCF客户端代理的常用方式。
然而,事情已经发生了变化。结果表明,IClientChannel<T>。Dispose()简单地调用IClientChannel<T>。Close()方法,在某些情况下,可能会抛出异常,例如当底层通道未打开或无法及时关闭时。
因此,在catch
块中调用Close()
不是一个好主意,因为在出现异常的情况下,这可能会留下一些未发布的资源。
推荐的新方法是调用IClientChannel<T>。在Close()
失败的情况下,改为在catch
块内中止()。这里有一个例子:
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;
}