问题描述
限时送ChatGPT账号..在他的WCF 服务编程"一书中,Juval Lowry 表达了对使用单例服务的担忧,因为它会影响性能.
In his book "Programming WCF Services", Juval Lowry expresses concerns about using Singleton Services because of the performance implications.
在我的一个项目中,我使用了一个无状态单例 WCF 服务,声明如下:
In one of my projects I'm using a stateless singleton WCF Service declared like this:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple)]
public class FooService : IFoo
{
}
从多个 Silverlight 客户端通过 httpsTransport 访问该服务.我选择了单例,因为我认为没有必要在不需要时给系统增加 GC 开销.我是否遗漏了某些东西,或者这不应该是实现无状态服务的最有效方法,该服务即使不比 PerCall 实例化服务更快,也同样快?
The service is accessed from multiple Silverlight clients over httpsTransport. I've opted for a singleton because I see no need to burden the system the GC overhead when it is not really needed. Am I missing something or shouldn't this be the most efficient way to implement a stateless service that's equally fast if not faster than a PerCall instantiated service?
推荐答案
您没有遗漏任何东西.如果您的服务类没有实例成员变量,这些变量代表的状态显然可能会被多线程访问破坏,那么就没有什么可担心的.
You're not missing anything. If your service class has no instance member variables, which would represent state that could obviously be corrupted by multi-threaded access, there is nothing to fear.
我个人总是使用 Single+Mulitple 模式,因为我的所有状态总是来自缓存或 SQL 数据库或其他一些共享资源,在这些资源中,您无论如何都需要模式来防止并发.我从未在我的服务中发现需要成员变量.静力学?当然可能,但你知道无论如何都要保护他们.
I personally always use Single+Mulitple mode because all of my state is always coming from a cache or SQL database or some other shared resource where you need patterns to guard against concurrency anyway. I've never found a need for member variables in my services. Statics? Sure maybe, but then you know to protect them anyway.
现在这是我个人对 PerCall 与 Single 的看法.PerSession 另一方面,服务可以/很可能会在实例中维护状态,但我个人发现自己并没有写很多这样的东西,而且在极少数情况下,它们是 ConcurrencyMode.Single无论如何.
Now this is all my personal opinion on PerCall vs. Single. PerSession services on the other hand could/most likely would have state maintained in the instance, but I personally don't find myself writing many of those and on the rare occasion I have, they are ConcurrencyMode.Single anyway.
查看这篇 MSDN 文章差异的更多讨论和实际性能比较.模式.
Check out this MSDN article for more discussion and actual performance comparison of the diff. Modes.
这篇关于多线程单例 WCF 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论