WCF REST服务:InstanceContextMode.PerCall无法正常工作

Cle*_*leo 5 rest wcf

我已经为WCF实现了一个REST服务.该服务提供了一个可被许多客户调用的功能,此功能需要1分钟以上才能完成.所以我想要的是,对于每个客户端,使用一个新对象,以便一次可以处理许多客户端.

我的界面如下所示:

[ServiceContract]
public interface ISimulatorControlServices
{
    [WebGet]
    [OperationContract]
    string DoSomething(string xml);
}
Run Code Online (Sandbox Code Playgroud)

并且(测试)实现它:

[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";
    }
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是:如果我使用创建10(或任何数量)线程的客户端,每个线程调用服务,它们不会同时运行.这意味着,呼叫是一个接一个地处理的.有人知道为什么会这样吗?

补充:客户端代码

产卵线程:

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

方法:

  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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Cle*_*leo 2

由于该服务是由 GUI 控制的,因此需要“UseSynchronizationContext”属性来解决该问题:

  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode=ConcurrencyMode.Multiple, UseSynchronizationContext=false)] 
Run Code Online (Sandbox Code Playgroud)