2014-09-19 77 views
0

我正在用C#开发一个应用程序。我创建了ServiceHost应用程序,它将托管wcf服务。 客户端将通过传递一些参数来调用ServiceHost.exe。 我已经尝试了下面的方式。C中的单例WCF服务#

static class ServiceHost 
    { 
     private static ITest channel = null; 

    static void Main(string[] args) 
     { 
      if (String.Compare(args[0], "dooperation", true) == 0) 
       { 
        NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport); 
        binding.ReceiveTimeout = TimeSpan.MaxValue; 
        EndpointAddress ep = new EndpointAddress(address); 

        channel = ChannelFactory<ITest>.CreateChannel(binding, ep); 

        channel.DoOpertion1(); 
        channel.Close() // close service 

        // Make sure the application runs! 
        Application.Run(); 
        GC.KeepAlive(m_singleInstance); 
       } 
       else if (String.Compare(args[0], "stop", true) == 0) 
       { 
        NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport); 

        binding.ReceiveTimeout = TimeSpan.MaxValue; 
        EndpointAddress ep = new EndpointAddress(address); 

        channel = ChannelFactory<ITest>.CreateChannel(binding, ep); 

        channel.DoOpertion2(); 

        channel.Close() // close service 
      // Exit Appli 
        Application.Exit(); 
       } 
     } 
    } 

所以我在这里创建通信频道,调用方法和关闭频道。 但创建名称管道,然后通信通道和服务通道消耗更多时间,所以我想优化调用,以便它将创建单个实例的WCF服务通信通道,每当客户端调用ServiceHost.exe。

有没有什么办法可以创建单个通道实例? 是否有任何副作用,如果我们保持打开namepine /沟通渠道。

回答

0

重复使用WCF通道是一种反模式,通道不是线程安全的,您必须处理故障状态。渠道的创建并不耗时,工厂的创建就是这样。所以你应该重用你的ChannelFactory。

MSDN Middle-Tier Client Applications

+0

感谢您的回复。您能否分享代码以重用渠道工厂? – user3106005 2014-09-20 17:34:16