如何测试网管服务是否正在监听

如何以编程方式测试以查看特定的网络管道服务是否正在运行和监听,因此我没有得到“没有端点监听……”exception?

所以,例如,如果我有这个代码:

Uri baseAddress = new Uri("http://localhost/something"); var _ServiceHost = new ServiceHost(typeof(Automation), new Uri[] { baseAddress }); NetNamedPipeBinding nnpb = new NetNamedPipeBinding(); _ServiceHost.AddServiceEndpoint(typeof(IAutomation), nnpb, "ImListening"); _ServiceHost.Open(); 

我希望从另一个应用程序与http://localhost/something/ImListening通信,但在我想确保正在监听之前我没有得到exception,或者是测试这个的唯一方法的exception?

听取例外情况。 这正确的方法。

exception存在是有原因的,我只会处理exception,只要你处理它,用户就不会得到一个神秘的错误消息,我想这是你想要避免的。

也许不是最好的方法,但我没有找到另一种使用NetNamedPipe测试端点的方法。

我通常采用这种方法:

  public void IsValid() { RegisterConfiguration(); var endPoints = Host.Description.Endpoints; if (!endPoints.HasElements()) { throw new NullReferenceException("endpoints (WCF Service)."); } foreach (var item in endPoints) { var service = new ChannelFactory(item.Binding, item.Address); try { var client = (IClientChannel)service.CreateChannel(); try { client.Open(TimeSpan.FromSeconds(2)); throw new InvalidOperationException( string.Format( "A registration already exists for URI: \"{0}\" (WCF Service is already open in some IChannelListener).", item.Address)); } catch (Exception ex) { if (ex is System.ServiceModel.CommunicationObjectFaultedException || ex is System.ServiceModel.EndpointNotFoundException) { Debug.WriteLine(ex.DumpObject()); } else { throw; } } finally { new Action(client.Dispose).InvokeSafe(); } } finally { new Action(service.Close).InvokeSafe(); } } } 

(对不起这段代码中的扩展方法, InvokeSafe只是一个try / catch来执行ActionHasElements只测试一个集合是否为null和空)。