Concurrency in WCF refers controlling number of threads in a given session context. ConcurrencyMode can be used with ServiceBehavior attribute.
Concurrency Modes
[ServiceContract]
Concurrency Modes
- Single: Only one thread allowed to run in a session context, multiple calls to service served one by one.
- Multiple: Multiple threads allowed to run in a session context so multiple calls to the service could be served simultaneously, calls could be from same client or different clients.To use this mode service should be designed thread safe. Operations on object's states(operations changing state of objects) should be locked, so that other thread couldn't access those in between operations.
- Reentrant: This is modified mode of 'Single'. Only one thread is allowed to run, any other call to the service in queue may start to serve when current one calls some other wcf service.So when proceed thread calls some other wcf service the thread released locks and other queued call may start.
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData();
}
[ServiceBehavior(InstanceContextMode= InstanceContextMode.PerCall, ConcurrencyMode= ConcurrencyMode.Multiple)]
public class Service1 : IService1
{
int instanceCount =0;
object thislock = new object();
public string GetData()
{
lock (thislock) //Loc is
important when you using "Multiple" concurrency mode
{
Thread.Sleep(1000);
return string.Format("Instance
Count:{0}, Session Id:{1}, Thread Name: {2}, Time: {3}", ++instanceCount, OperationContext.Current.SessionId, Thread.CurrentThread.Name, DateTime.Now.ToString());
}
}
}











