WCF REST service: InstanceContextMode.PerCall not working

I implemented a REST service for WCF. The service offers one function that many customers can call, and it takes more than 1 minute to complete this function. Therefore, I wanted a new object to be used for each client, so that many clients can be processed simultaneously.

My interface is as follows:

[ServiceContract]
public interface ISimulatorControlServices
{
    [WebGet]
    [OperationContract]
    string DoSomething(string xml);
}

And its (test) implementation:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall]
public class SimulatorControlService : SimulatorServiceInterfaces.ISimulatorControlServices
{
    public SimulatorControlService()
    {
        Console.WriteLine("SimulatorControlService started.");
    }

    public string DoSomething(string xml)
    {
        System.Threading.Thread.Sleep(2000);
        return "blub";
    }
}

Now the problem is this: if I use a client that creates 10 (or as many as you like) threads, each of which calls the service, they do not start at the same time. This means that calls are processed one after another. Does anyone have an idea why this is happening?

Added: client code

Spawning streams:

        for (int i = 0; i < 5; i++)
        {
            Thread thread = new Thread(new ThreadStart(DoSomethingTest));
            thread.Start();
        }

Method:

  private static void DoSomethingTest()
    {
        try
        {
            using (ChannelFactory<ISimulatorControlServices> cf = new ChannelFactory<ISimulatorControlServices>(new WebHttpBinding(), "http://localhost:9002/bla/SimulatorControlService"))
            {
                cf.Endpoint.Behaviors.Add(new WebHttpBehavior());

                ISimulatorControlServices channel = cf.CreateChannel();

                string s;

                int threadID = Thread.CurrentThread.ManagedThreadId;

                Console.WriteLine("Thread {0} calling DoSomething()...", threadID);

                string testXml = "test";

                s = channel.StartPressureMapping(testXml);

                Console.WriteLine("Thread {0} finished with reponse: {1}", threadID, s);
            }

        }
        catch (CommunicationException cex)
        {
            Console.WriteLine("A communication exception occurred: {0}", cex.Message);
        }
    }

Thanks in advance!

+5
source share
1 answer

Since the service is controlled by a graphical interface, the "UseSynchronizationContext" attribute is required to solve the problem:

  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode=ConcurrencyMode.Multiple, UseSynchronizationContext=false)] 
+1
source

All Articles