C# - 测试 Internet 页面 - 等待超时 [英] C# - Testing Internet page - Waiting for timeout
问题描述
为了测试我们的计算机是否连接到防火墙,我们检查此防火墙的登录网页是否打开.如果超时,错误处理会说它已连接,如果它打开(或在我们的例子中抛出证书错误),我们知道我们没有连接.
To test if our computer is connected to a firewall we check if the loginwebpage for this firewall opens. If it times out, the error handling will say it's connected, if it opens (or throws a certificate error as it does in our case) we know we are not connected.
这个过程的一个大问题是,只要我们已经连接,应用程序就会挂起,直到网页超时..
The big problem with this process is that whenever we are already connected, the application hangs until the webpage times out..
欢迎任何输入,这是我使用的代码:
Any input is more than welcome, here's the code I use:
public static bool FirewallConnectivityStatus(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Proxy = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (HttpStatusCode.OK == response.StatusCode)
{
response.Close();
return false;
}
else
{
return true;
}
}
catch (WebException Ex)
{
if (Ex.Status == WebExceptionStatus.TrustFailure)
{
return false;
}
else
{
return true;
}
}
}
更新与此同时,我发现了一个套接字连接,它可以让我更好地通过 IP 而不是 url 创建此连接:C# - 用于登录防火墙的套接字
推荐答案
也许使用 BackgroundWorker 可以:
Maybe using a BackgroundWorker could work:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
他们在那个页面上有一个相当不错的例子.我以前从没想过要测试这个.我想不出一个简单的方法来测试它.看起来之前也有人问过它:
They have quite a decent example on that page. I've never thought about trying to test this before. I cannot think of a simple way to test it. It looks like its been asked before as well:
至少后台工作者可以让你的程序在等待超时的同时继续.这仅取决于您是否可以让应用在您测试时继续运行而无需回答.
At least the background worker could let your program continue while waiting for the timeout. It just depends if you can let the app continue at the point you are testing it without an answer.
如何减少超时时间?http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.timeout.aspx
这篇关于C# - 测试 Internet 页面 - 等待超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!