开发者

Multithreaded Singleton WCF Service

In his book "Programming WCF Services", Juval Lowry expresses concerns about using Singleton Services because of the performance implications.

In one of my projects I'm using a stateless singleton WCF Service declared like this:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
   ConcurrencyMode = Co开发者_开发技巧ncurrencyMode.Multiple)]
public class FooService : IFoo
{
}

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?


Your assumption probably holds true for a WCF service configured for basicHttpBinding with no SSL (see here for more info) but that is not likely true for other bindings. Although your application code may truly be stateless and/or thread safe, WCF uses sessions internally to support functionally in other bindings. This implies only one session per request can be handled since there is only a single service instance.

Seems like picking the singleton pattern is a case of premature optimization. Optimizing for GC efficiency should only be a concern when you have a proven need.


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.

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.

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.

Check out this MSDN article for more discussion and actual performance comparison of the diff. Modes.


One of the reasons that you'd want to avoid singletons is because generally you'd have a shared resource that you MUST make thread safe. Once you do that, you have the possibility of stacking up service calls in a serial queue since only one call will be allowed in that critical section at once.

Since you have a stateless singleton, that probably won't be an issue. It would, however, make it easy for that sort of thing to occur later on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜