WCF REST 服务 : InstanceContextMode. PerCall 不工作

标签 wcf rest

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

我的界面是这样的:

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

以及它的(测试)实现:
[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";
    }
}

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

补充:客户端代码

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

方法:
  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);
        }
    }

提前致谢!

最佳答案

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

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

关于WCF REST 服务 : InstanceContextMode. PerCall 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12529724/

相关文章:

wcf - 在 ASMX Web 服务上使用 WCF 有什么好处?

rest - 如果我需要额外的 REST API,Meteor 是一种选择吗?

json - 如何在 golang 中将字符串值作为 json 对象返回?

rest - 在 REST API 中只允许 GET

java - 带有 json/xml 响应的嵌入式 jetty

c# - 无法将类型 'bool' 隐式转换为 'system.threading.tasks.task bool'

wcf - SvcUtil.exe 的替代品?

wcf - Silverlight WCF + SSL 安全错误 - 从未请求过 crossdomain.xml

Internet 上的 WCF 事务

api - REST API - 在单个请求中批量创建或更新