【发布时间】:2012-03-07 22:34:43
【问题描述】:
我正在重构一个通过 wcf 进行进程间通信的大型程序。由于客户端可以直接访问服务接口,因此使用通道工厂来创建通道,因此不需要额外的客户端服务存根。通信包含许多高频请求的大消息(当前使用 NetTcpBinding,我正在考虑切换到 NetNamedPipeBinding)。
我的问题是关于创建/关闭频道与创建/关闭频道工厂之间的区别。更准确地说:channelfactory 创建了一个通道。现在,关于单个请求:我应该创建和关闭 channelfactory 以及与单个请求相关的通道(参见解决方案 2)还是仅创建/在性能方面更安全/更好?关闭与单个请求相关的通道,并使通道工厂为多个请求打开(参见解决方案 1)。
1)
//set up the channel factory right when I start the whole applicaton
ChannelFactory<IMyService> cf = new ChannelFactory<IMyService>();
//call this trillion of times over time period of hours whenever I want to make a request to the service; channel factory stays open for the whole time
try
{
IMyService myService = cf.CreateChannel();
var returnedStuff = myService.DoStuff();
((IClientChannel)myService).Close();
}
catch ...
//close the channel factory when I stop the whole application
cf.Close();
2)
//call this trillion of times over time period of hours whenever I want to make a request to the service
try
{
ChannelFactory<IMyService> cf = new ChannelFactory<IMyService>();
IMyService myService = cf.CreateChannel();
var returnedStuff = myService.DoStuff();
cf.Close();
}
catch ...
有什么实际区别?正确的方法是什么?还有更好的选择吗?
【问题讨论】:
-
您使用什么绑定来与服务通信?
-
ChannelFactory<T>实现IDisposable,其清理应由using语句处理。 -
目前使用 nettcp 作为绑定。我正在考虑切换到命名管道,但考虑到当前架构,这将是一个重大变化。
-
我正在使用带有关闭/中止的 try-catch 模式。我已经阅读了推荐用于 wcf 而不是 using 语句的内容,因为对 close 的调用可能会导致异常。 stackoverflow上有几个关于这个的线程。但我的问题是关于关闭通道与通道工厂的区别。所以它是关于什么时候关闭,而不是关于如何关闭。我更正了我最初的问题,希望它变得更清楚。
标签: c# wcf channel channelfactory