C# 检查 WCF 服务是否正在运行的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18020506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Quickest way to check if WCF service is running
提问by NMunro
I have a WCF service running locally. The service has a default port that it runs on, but if that port is already in use then I assign the port dynamically.
我有一个在本地运行的 WCF 服务。该服务有一个运行的默认端口,但如果该端口已被使用,那么我会动态分配该端口。
I added this in the host to make it discoverable:
我在主机中添加了它以使其可发现:
serviceHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());
Now my client needs to connect to this host. In the client I want to have it first try the default port, and if it can't connect to the service on the default port, then it will do the discovery.
现在我的客户端需要连接到这台主机。在客户端我想让它先尝试默认端口,如果它无法连接到默认端口上的服务,那么它就会进行发现。
I've found that the discovery takes about 20-30 seconds, so I would prefer to avoid always doing it, only when it can't find the host on the default port.
我发现发现大约需要 20-30 秒,所以我宁愿避免总是这样做,只有当它在默认端口上找不到主机时。
So my question is: what is the quickest way to determine if my host is on the default port?
所以我的问题是:确定我的主机是否在默认端口上的最快方法是什么?
I was thinking about doing something like setting the open timeout on the client to 10 seconds, and then doing a try/catch on open, but that still requires waiting 10 seconds.
我正在考虑做一些事情,比如将客户端的打开超时设置为 10 秒,然后在打开时执行 try/catch,但这仍然需要等待 10 秒。
采纳答案by NMunro
So, calling client.Open();
will not throw any exceptions if your endpoint is incorrect.
因此,client.Open();
如果您的端点不正确,调用不会引发任何异常。
I added a method in my service called IsAlive()
which simply returns true. So I call client.IsAlive();
after opening and if the endpoint is incorrect there will be an exception almost instantly.
我在我的服务中添加了一个方法,该方法IsAlive()
只返回 true。所以我client.IsAlive();
在打开后调用,如果端点不正确,几乎会立即出现异常。
回答by Brian
You can actually just navigate to the URL in a browser, which should show you if the web service is running. So if the WCF url is
实际上,您只需导航到浏览器中的 URL,它就会显示 Web 服务是否正在运行。所以如果 WCF 网址是
http://YourService:8000/YourClass/YourMethod
, the typing that into address bar of a browser should show you the WSDL page if the service is running, a 404 error if not.
,如果服务正在运行,则在浏览器的地址栏中键入它应该会显示 WSDL 页面,否则会显示 404 错误。
My WCF service is self hosted, so I'll add, too, that when my WCF service starts, I use a this line of code to output into a DOS windows what the current URL of my service is:
我的 WCF 服务是自托管的,所以我还要补充一点,当我的 WCF 服务启动时,我使用这行代码将我的服务的当前 URL 输出到 DOS 窗口:
Console.WriteLine("HostInterface running on http://" & Domain & ":" & Port & "/Service/Endpoint" )