检查如果网络服务已经启动并运行 - 高效 [英] check to if web-service is up and running - efficiently
问题描述
我做以下,
var request = (HttpWebRequest)WebRequest.Create(serviceUrl);
var response = (HttpWebResponse)request.GetResponse();
if(response.StatusCode == HttpStatusCode.OK)
{
//perform some operations.
}
为了检查一下了,在我的asp.net C#4.0的应用程序运行的服务。
它给我的预期结果,但如果服务没有运行它花费过多时间(将近约1分钟)获得响应。
in order to check if the service in up and running in my asp.net c# 4.0 application. its giving me expected results but if the service is not running it is taking too much time (nearly about 1 min) to get the response.
是他们的任何其他更好的方法来检查服务是否启动并运行?
is their any other better way to check if the service is up and running?
推荐答案
您不必做更多的事情比你已经在做,除了超时添加到您的请求对象。请求超时应以毫秒为单位,因此 5000
为5秒超时。
You don't have to do much more than you are already doing, other than add a timeout to your request object. The request timeout should be specified in milliseconds, so 5000
for a 5 second timeout.
要知道,那么你将需要捕捉异常检测超时,这是一个 System.Net.WebException
的消息操作已超时
,所以你的code看起来是这样的:
Be aware you will then need to catch the exception to detect the timeout, this is a System.Net.WebException
with the message The operation has timed out
, so your code will look something like:
var request = (HttpWebRequest)WebRequest.Create(serviceUrl);
request.Timeout = 5000;
try
{
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
//perform some operations.
}
}
catch (WebException wex)
{
if (wex.Message == "The operation has timed out")
{
// do stuff
}
}
这篇关于检查如果网络服务已经启动并运行 - 高效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!