WCF InstanceContextMode, Concurrency Modes, Throttling

A WCF service developers perspective it is important to understand how the instances of our WCF service class is being created and how will it effect the overall service operations. WCF provides us the possibility of configuring the service behavior in terms of instance creation modes and understanding all the instance modes is really important to configure our WCF service to work in proper manner. So let us look at how the instance management for the WCF service works and how we can configure it as per our needs.


There are three possible ways of configuring WCF instances.

  1. PerCall
  2. PerSession
  3. Single

The PerCall mode says that this WCF service class instance will be created on every function call. These function calls could be from same client or different client. Whenever a function call is made from the client application a WCF service class instance is created, the function is called and the instance is disposed. Now if the same or any other client call the same or any other method of the service a new instance will be created and there is no way to reclaim the old instance.

The PerSession instance mode specifies that one instance of WCF service class will be created for each client. So if the client remains active and make multiple calls to the same or multiple methods of the service then the instance created for this particular client will be reused. Now this comes in very handy when we need to have some sequence of operations performed on the service and state of the service needs to be preserved between the calls.

The Single mode specifies that there will be only one instance for the WCF service class for all the clients. It is more like having a singleton class that will be used by all the clients.

Note: One important thing to note for the PerSession mode is that it has dependency on the protocol being used to access the service. If the service is being accessed via http i.e. basicHttpBinding then PerSessionmode will not work because the http itself is stateless at the protocol level and thus the stateful configuration of PerSession will not work. In such cases, to have the stateful behavior, the service class will have to implement additional logic to save and reload the clients state across method calls.

To configure the instance mode we need to specify the ServiceBehavior attribute of the WCF service class implementation with the InstanceContextMode value. The value could beInstanceContextMode.PerCall, InstanceContextMode.PerSession andInstanceContextMode.Single respectively for the above mentioned modes.

WCF Concurrency Modes

WCF Concurrency modes gives us the possibility of taking control over these thread creation process so that a WCF service creator can take better, desirable and perhaps more control on the WCF service behavior.

Let us now look at the various possible concurrency modes:

  1. Single
  2. Multiple
  3. Reentrant


In Single mode, there will be only one thread that can use the instance of WCF service class. If any thread has already created an instance of the class then further requesting threads can create the instance but they will have to wait for first thread to finish using its instance and then it will get a change to execute the operation on its instance.

This is the default mode and this mode is safest from the concurrency perspective as the developer will not have to take care of concurrency issues in the code.

This mode can be visualized as that before calling each function the thread acquires a lock and after the call is complete the thread releases the lock so that other thread can proceed with the execution.

Now since this mode allows only one thread to process the instance at a time, this behavior will be same irrespective of the instance mode. i.e. in InstanceContextMode.Single,InstanceContextMode.PerSession and InstanceContextMode.PerCall only a single thread will be allowed to access the instance of the WCF service class.


In Multiple mode, each thread will have its own instance of the WCF service object and they all will be executing at the same time. Now this is the most complicated mode because all the concurrency issues must be handled by the service.

Now let us see what is the behavior with various InstanceContext Modes:

  • InstanceContextMode.Single: In this mode, only one instance will serve all the client requests and since the ConcurrencyMode is also set to Multiple, multiple threads will be created for all the clients.
  • InstanceContextMode.PerSession: Now in this mode, single instance of the service will be created for each client and since the ConcurrencyMode is set to Multiple, mulitple threads can be created for each client request.
  • InstanceContextMode.PerCall: Now in this mode a new instance is created for every call soConcurrencyMode set as Multiple will not have much impact on behavior and every call will be processed in a single thread.


The Reentrant mode is similar to the Single mode in a way that each thread can create its own instance but to execute the instance, they will have to wait for any other thread to finish using the instance. The main difference in this mode is that if the first thread’s instance either calls some other service or process the client callback, the second thread’s instance will be given a chance to execute.

Now since this is similar to Single mode and allows only one thread to process the instance at a time, this behavior will be same irrespective of the instance mode. i.e. in InstanceContextMode.Single,InstanceContextMode.PerSession and InstanceContextMode.PerCall only a single thread will be allowed to access the instance of the WCF service class but as soon as the instance calls any other service or go for processing client callbacks, the other thread will get a chance to execute its own instance of WCF service class.

Note: We have only talked about the ConcurrencyModes from a theoretical perspective. In most cases theConcurrencyMode.Single is used. Also, it in a stateless scenario, where the default instance mode is PerCall, making a change in the ConsurrencyMode will not have any effect/impact and thus there will rarely be a case when we would want to change the default behavior of the concurrency mode (and even if we change it, it will be futile).

WCF Throttling

Setting the InstanceContextMode and ConcurrencyMode will take care of the service behavior. But how should or could be address the issues related to number of clients accessing the service, the number of threads that can access the service or for instance the number of sessions that are allowed to be created for this service.

If we can take control on such issues then we can be sure that our service will behave in a consistent fashion even if it is being over consumed in terms of requests, sessions and/or calls.

WCF throttling gives us the possibility f specifying and configuring these limits to protect the service from over consumption. We can use the ServiceThrottle class to set these limits via code(imperatively) or we can set these in the serviceBehavior section of the service’s web.config file(declaratively). The major properties that can be set are:

  • MaxConcurrentSessions
  • MaxConcurrentInstances
  • MaxConcurrentCalls

Original Links





WCF REST Servcies




What is the difference between WCF and ASMX Web Services?

Simple and basic difference is that ASMX or ASP.NET web service is designed to send and receive messages using SOAP over HTTP only. While WCF can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, NamedPipes etc).

You can follow another tutorial WCF Vs ASMX for detailed discussion on this topic.


What are WCF Service Endpoints? Explain.

For Windows Communication Foundation services to be consumed, it’s necessary that it must be exposed; Clients need information about service to communicate with it. This is where service endpoints play their role. Client uses endpoint to communicate with WCF Service. A WCF serviceendpoint has three basic elements i.e. Address, Binding and Contract.

  • Address:It defines “WHERE”. Address is the URL that identifies the location of the service.
  • Binding:It defines “HOW”. Binding defines how the service can be accessed.
  • Contract:It defines “WHAT”. Contract identifies what is exposed by the service.


A WCF Service can have multiple endpoints configured to accommodate different clients, for example, one client may be using HTTP while other configured to communicate over TCP.


What are the possible ways of hosting a WCF service? Explain.

For a Windows Communication Foundation service to host, we need at least a managed processa ServiceHost instance and an Endpoint configured. Possible approaches for hosting a service are:

  • Hosting in a Managed Application/ Self Hosting
    • Console Application
    • Windows Application
    • Windows Service
  • Hosting on Web Server
    • IIS 6.0 (ASP.NET Application supports only HTTP)
    • Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP,
      NamedPipes, MSMQ.

If you are looking for implementation of all Hosting options, please follow here (Console | Windows Service | IIS WAS)


How we can achieve Operation Overloading while exposing WCF Services?

By default, WSDL doesn’t support operation overloading. Overloading behavior can be achieved by using “Name” property of OperationContract attribute.

 interface IMyCalculator
        [OperationContract(Name = “SumInt”)]
        int Sum(int arg1,int arg2);
        [OperationContract(Name = “SumDouble”)]

        double Sum(double arg1,double arg2);

When the proxy will be generated for these operations, it will have 2 methods with different names i.e. SumInt and SumDouble.

Important Note: Remember that during a technical Interview, interviewer always ask about the latest feature of that particular technology, so be prepare for it also. For latest features series on Windows Communication Foundation v4.5, Click here.


What Message Exchange Patterns (MEPs) supported by WCF? Explain each of them briefly.

  1. Request/Response
  2. One Way
  3. Duplex

It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.

One Way
In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. OneWay MEP will work in such scenarios.
If we want queued message delivery, OneWay is the only available option.

The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.

Please follow for detailed implementation for Message Exchange Patterns in WCF here.



What is DataContractSerializer and How its different from XmlSerializer?

Serialization is the process of converting an object instance to a portable and transferable format. So, whenever we are talking about web services, serialization is very important.

Windows Communication Foundation has DataContractSerializer that is new in .NET 3.0 and uses opt-in approach as compared to XmlSerializer that uses opt-out. Opt-in means specify whatever we want to serialize while Opt-out means you don’t have to specify each and every property to serialize, specify only those you don’t want to serialize.
DataContractSerializer is about 10% faster than XmlSerializer but it has almost no control over how the object will be serialized. If we wanted to have more control over how object should be serialized that XmlSerializer is a better choice.


How we can use MessageContract partially with DataContract for a service operation in WCF?

MessageContract must be used all or none. If we are using MessageContract into an operation signature, then we must use MessageContract as the only parameter type and as the return type of the operation.


Which standard binding could be used for a service that was designed to replace an existing ASMX web service?

The basicHttpBinding standard binding is designed to expose a service as if it is an ASMX/ASP.NET web service. This will enable us to support existing clients as applications are upgrade to WCF.


Please explain briefly different Instance Modes in WCF?

WCF will bind an incoming message request to a particular service instance, so the available modes are:

  • Per Call: instance created for each call, most efficient in term of memory but need to maintain session.
  • Per Session: Instance created for a complete session of a user. Session is maintained.
  • Single: Only one instance created for all clients/users and shared among all.Least efficient in terms of memory.

Please follow “3 techniques for Instance Management in WCF“.


Please explain different modes of security in WCF? Or Explain the difference between Transport and Message Level Security.

In Windows Communication Foundation, we can configure to use security at different levels

  1. Transport Level securitymeans providing security at the transport layer itself. When dealing with security at Transport level, we are concerned about integrity, privacy and authentication of message as it travels along the physical wire. It depends on the binding being used that how WCF makes it secure because most of the bindings have built-in security.

         <binding name=”netTcpTransportBinding”>
                    <security mode=”Transport”>
                          <Transport clientCredentialType=”Windows” />

  1. Message Level Security
    For Tranport level security, we actually ensure the transport that is being used should be secured but in message level security, we actually secure the message. We encrypt the message before transporting it.

            <binding name=”wsHttpMessageBinding”>
                          <security mode=”Message”>
                                     <Message clientCredentialType=”UserName” />

It totally depends upon the requirements but we can use a mixed security mode also as follows:

             <binding name=”basicHttp”>
                          <security mode=”TransportWithMessageCredential”>
                               <Transport />
                               <Message clientCredentialType=”UserName” />


Choosing an Appropriate WCF binding

 Depending upon your requirements, you can choose a binding for your service as shown below in the diagram:



BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You’re comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn’t have anything like that – yet). On the other hand, you can’t just browse to a wsHttpBinding endpoint with your browser and look at XML – you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service – that’s possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding – SOAP 1.1, not much in terms of security, not much else in terms of features – but compatible to just about any SOAP client out there –> great for interoperability, weak on features and security
  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards – it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control – just a lot more stuff, but wsHttpBinding is also a lot *heavier” and adds a lot of overhead to your messages as they travel across the network
  1. No comments yet.
  1. No trackbacks yet.

Thanks for your comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: