Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF REST Service: InstanceContextMode.PerCall not working

Tags:

rest

wcf

I have implemented a REST service for WCF. The service offers one function that can be called by many clients and this function takes more than 1 minute to complete. So what I wanted is that for each client, a new object is used, so that many clients can be handled at a time.

My interface looks like this:

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

And the (test) implementation of it:

[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";
    }
}

The problem now is: if I use a client that creates 10 (or whatever number) threads, each of it calling the service, they dont run concurrently. This means, the calls are being handled one after each other. Does anybody have an idea why this happens?

Added: client-side code

Spawning threads:

        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!

like image 539
Cleo Avatar asked Nov 03 '22 15:11

Cleo


1 Answers

Since the service is controlled by a GUI, the "UseSynchronizationContext" attribute was needed to solve the problem:

  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode=ConcurrencyMode.Multiple, UseSynchronizationContext=false)] 
like image 63
Cleo Avatar answered Nov 15 '22 07:11

Cleo