带有命名管道的WCF:如何允许并行调用?

问题描述 投票:0回答:1

这是我使用WCF和命名管道的第一种方法。

[我要做的是一个Windows服务在一个命名管道上侦听,而一个小的GUI告诉它通过管道做什么。

一切正常:对服务进行调用,将响应传递到GUI,然后完成工作。但是,如果我从GUI发送两个并发请求,则该服务将一个接一个地处理它们:我想手动管理并发服务端,并使其同时运行两个请求。

我尝试为2个请求创建2个不同的管道,它满足了我的需要,但当然不是解决方案。

我正在使用.NET Framework 4.0,但无法更改。

这是我的示例代码:

SERVICE:管道配置

ServiceHost host = new ServiceHost(typeof(CommandReceiver), new Uri[] {new Uri("net.pipe://localhost") });            
host.AddServiceEndpoint(typeof(ICommandReceiver), new NetNamedPipeBinding(), "myPipe");
host.Open();

SERVICE:合同接口和实施

[ServiceContract]
public interface ICommandReceiver
{
    [OperationContract]
    string Foo();

    [OperationContract]
    string Bar();
}

public class CommandReceiver : ICommandReceiver
{
    public string Foo()
    {
        //Do stuffs
        System.Threading.Thread.Sleep(3000);
        return "FOO";
    }

    public string Bar()
    {
        //Do stuffs
        System.Threading.Thread.Sleep(3000);
        return "BAR";
    }
}

客户端:管道配置

ChannelFactory<ICommandReceiver> pipeFactory = new ChannelFactory<ICommandReceiver>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/myPipe"));
ICommandReceiver serviceProxy = pipeFactory.CreateChannel();

客户:致电服务

public string GetFoo() 
{
    return serviceProxy.Foo();
}
public string GetBar() 
{
    return serviceProxy.Bar();
}

关于如何改善整体效果的任何建议,甚至切换到另一种交流方法,都将非常感激。

非常感谢!

c# wcf named-pipes
1个回答
0
投票

[确定,我已经解决了这个问题:首先,我在合同实现类上缺少以下属性:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
public class CommandReceiver : ICommandReceiver
{
  public string Foo()
  {
    //Do stuffs
    System.Threading.Thread.Sleep(3000);
    return "FOO";
  }

  public string Bar()
  {
    //Do stuffs
    System.Threading.Thread.Sleep(3000);
    return "BAR";
  }
}

然后我发现该服务可以正常运行,但是不是在Visual Studio中调试时。发行并将其安装在系统上可以解决此问题。

© www.soinside.com 2019 - 2024. All rights reserved.