我正在使用以下方式关闭 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 的“早期”发布 WCF 客户端代理的普遍接受的方式。
然而,事情已经发生了变化。事实证明,IClientChannel<T>.Dispose()的实现只是调用了IClientChannel<T>.Close()方法,在某些情况下可能会抛出异常,例如当底层通道未打开或无法打开时不及时关闭。
因此,Close()
在catch
块内调用不是一个好主意,因为在发生异常时可能会留下一些未释放的资源。
新的推荐方法是在块内调用IClientChannel<T>.Abort()catch
,以防万一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;
}