WCF 客户端 - 客户端何时应关闭通道
在典型的客户端服务应用程序中,服务是 WCF,如何使用服务引用?
例如,您是否为每个调用单独实例化服务,或者是否打开一个服务并在客户端应用程序的整个生命周期中保留它? (当我提到“实例化服务”时,我的意思是实例化由 svcutil 创建的服务对象)
现在我们在客户端上使用一个服务实例,因为这似乎比每次调用时创建、打开和关闭服务都要快,但现在我想知道这样可以吗?这种方法的主要问题是发生超时(或者我们必须打开会话 10 小时)、连接中断等,并且我们始终必须通过通道执行“IsAlive”以确保一切正常...
如果应用程序是单线程的,并且身份验证是自定义构建的(通过将身份验证令牌插入标头)。绑定是 basicHttp (或 ws,对于这种情况并不重要)。
In a typical client-service application, where service is WCF, how to you use the service reference?
For example, do you instantiate service for each call separately, or do you open one and keep it through the lifetime of the client app? (when I'm refering to 'instatiating service', I mean instantiate service object created by svcutil)
For now we used one service instance on client, because that seemed faster than always creating, opening and closing the service for each and every call, but now I wander if that was OK? The main problem we have with this approach is that timeouts occur (or we have to have sessions opened for 10hrs), connection breaks etc, and we always have to do 'IsAlive' through the channel to make sure everything is fine...
If it's of any relevance the app is single threaded, and the authentication is custom built (by inserting auth tokens into header). The binding is basicHttp (or ws, doesn't really matter for this case).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就我个人而言,我更喜欢保持通道打开直到方法调用返回,然后将其关闭以释放资源。这是所有方法中最干净的方法。每次初始化代理实例只需几毫秒,并且从未影响我的性能目标。
拥有某种 ServiceClient 单例是一个有趣的想法,但正如您所说,它会带来很多副作用,所以我不确定这是一个明智的方法,但由于您的应用程序是单线程的,那么它不应该是一个大的问题问题,您可能会获得一些轻微的性能优势。
如果节省毫秒是关键任务,那么您还可以拥有一个可以从中获取实例的 ServiceClient 池。
然而,第一种方法是最干净的。复杂性不好。
Personally i prefer to keep the channel open just until the method call returns and then close it to free resources. It is the cleanest approach of all. Initializing the proxy instance each time is matter of milliseconds and never affected my performance goals.
Having some kind of ServiceClient singleton is an interesting idea, but as you stated, it comes with a lot of side effects, so i am not sure that's a smart approach, but since your app is single threaded, then it should not be a big issue and you will probably have some slight performance benefits.
If saving milliseconds is mission-critical, then you could also have a pool of ServiceClients that you could get instances from.
However, the first approach is the cleanest. Complexity is bad.