There are three InstanceContextMode in WCF.
- PerCall: a new InstanceContext object is created and recycled succeeding each call.
- PerSession: A new InstanceContext object is created per session and instance is not sharable by multiple sessions.
- Single: A single instance is created and used for all incoming calls.
There are three ConcurrencyMode supported by WCF.
- Single: The service instance is single threaded and does not accept reentrance calls. If a new message comes when another message is being processed, this message has to wait there until the first one is finished.
- Multiple: The service is multi-threaded. It is fast. No waiting. But developer has to make sure the code is thread-safe.
- Reentrance: The service is single threaded and can accept reentrant calls. It implies that the service processes only one message at a given time. To ensure thread safety, WCF locks the InstanceContext processing a message so that no other messages can be processed. In case of Reentrant mode, the InstanceContext is unlocked just before the service makes an outgoing call thereby allowing the subsequent call to get the lock next time it comes in to the service.
There are many factors we should think about when choosing service behavior.
- Constructor of service. Probably InstanceConxt. Single should be used if there are lots of stuff to load and initialize. InstanceContext.PerSession should be used if there are states to maintain for one client. No thing to maintain for different calls, different clients, InstanceContext.PerCall should be used.
- ConcurrencyMode does not matter if InstanceContextMode.PerCall is adopted. New available thread will be used if new call comes.
- InstanceContext.PerCall and InstanceContext.PerSession mean same thing if there is no session maintained for this service
- ConcurrencyMode.Reentrant does not mean multiple thread. It is single thread in most cases except there is outgoing service call.
- Take care of thread-saftety if InstanceContextMode.Single and ConcurrencyMode.Multiple are considered to use. It will be faster and it will also be tricky.
We could put some logs to know when the object is initialized and which thread is used in the constructor. Just for confirmation.
No comments:
Post a Comment