Search code examples
.netmultithreadingwcfoperationcontext

OperationContext.Current.SessionId in multithreading environment


I have a WCF service which connect to multiple clients. The service is configured as follows:

ServiceBehavior(
        InstanceContextMode = InstanceContextMode.Single,
        UseSynchronizationContext = false,
        ...

in the service I use identify clients using OperationContext.Current.SessionId.

public void Register()
{
        Debug.WriteLine(OperationContext.Current.SessionId);
}

Imagine the following scenario: - Client1 calls Register - The service runs Register in Thread1 - After a certain time Client2 calls Register - The service runs Register also in Thread1 (which is theoretically possible, no?)

Knowing that OperationContext.Current is ThreadStatic, What's display the second call :

  • Session 1 because OperationContext.Current is already set in the first call
  • Or Session 2 ..?

Thank you in advance ...


Solution

  • You will get Session2. Session and Instantiation are 2 different things in WCF. I would recommend you read the following 2 blog entries that will help you understand the concepts of WCF sessions and instantiation.

    http://www.dotnetconsult.co.uk/weblog2/PermaLink,guid,af6e6325-2e30-42e3-acb9-57e1363fa51e.aspx

    http://www.dotnetconsult.co.uk/weblog2/PermaLink,guid,1efac821-2b89-47bb-9d27-48f0d6347914.aspx

    you can also test this with a client. I changed your WCF method to return the sessionID and consumed it in the client.

    static void Main(string[] args)
    {
          ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
          Console.WriteLine(client.Regster());
          Console.ReadLine();
          client.Close();
    }