【问题标题】:singleton WCF service in C#C# 中的单例 WCF 服务
【发布时间】:2014-09-19 12:03:41
【问题描述】:

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

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(); 
               }
        }
   }

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

有什么方法可以创建单个频道实例吗? 如果我们保持打开namepine/通信通道有什么副作用吗?

【问题讨论】:

    标签: wcf singleton


    【解决方案1】:

    重用 WCF 通道是一种反模式,通道不是线程安全的,您必须处理错误状态。通道的创建并不耗时,工厂的创建是。所以你应该重用你的 ChannelFactory。

    MSDN Middle-Tier Client Applications

    【讨论】:

    • 感谢您的回复。您能否分享代码以重用通道工厂。
    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多