Thursday, February 27, 2014

WCF Concurrency and Instances

A quick tidbit regarding WCF in terms of performance.

You may be used to using the [ServiceContract] attribute to decorate your WCF method without giving it a second thought.  Then as time goes on you may notice that as more users hit your service the performance isn't what you were expecting.

One of the drawbacks to just using [ServiceContract] is that be default it is to create a new instance of your service which only handles one call.  This is fine if you need to do session management but in many cases a REST service will not.

A good practice is to decorate your methods with [ServiceBehavior] which allows you to change how the service operates. By using this behavior and settings the InstanceContextMode to Single you now have a service where all clients calling will use the same instance.  So if you are caching data then the performance from that can be realized.  In the default mode each client gets its own instance which takes up memory and doesn't serve anyone except the same caller on sequent calls.

Note: You thread safety becomes important in this case.

You can also change the ConcurrencyMode to determine how a call is handled.  In Single mode only one call is handled at a time.  So if you had a method that returned a number that is incremented continually, no call would get the same number because each call would wait until previous calls completed.

In a Multiple concurrency mode you would have to wrap the incrementing number with a lock or other thread safe mechanism otherwise you might get a conflict or deadlock because too many operations are trying to perform operations against the simple number field.

There is a 3rd mode called Reentrant which would be a special case that I've chosen not to cover here.

So in summary, look at adding the InstanceContextMode and ConcurrencyMode attributes found in the ServiceBehavior attribute instead of just a ServiceContract attribute to better control how your WCF service operates and to tweak performance based on how you need to service to scale/perform.

No comments:

Post a Comment