我正在处理的程序中的互联网连接有很多麻烦,而这一切似乎都是由代理设置的某些问题产生的.此时的大多数问题都已修复,但我现在遇到的问题是我的代理设置测试方法会让一些用户等待很长时间.
这是我做的:
System.Net.WebClient webClnt = new System.Net.WebClient();
webClnt.Proxy = proxy;
webClnt.Credentials = proxy.Credentials;
byte[] tempBytes;
try
{
tempBytes = webClnt.DownloadData(url.Address);
}
catch
{
//Invalid proxy settings
//Code to handle the exception goes here
}
Run Code Online (Sandbox Code Playgroud)
这是我发现测试代理设置是否正确的唯一方法.我尝试对我们的Web服务进行Web服务调用,但在拨打电话时不需要代理设置.即使我有伪造的代理设置,它也会工作.但是,上面的方法没有我可以设置的超时成员,我可以使用DownloadData而不是DownloadDataAsync,因为我需要等待方法完成,以便我可以在继续之前知道设置是否正确在该计划中.
任何关于更好的方法或解决方法的建议都值得赞赏.
麦克风
编辑:我尝试了其他的东西,但没有运气.我使用DownloadDataAsync方法在一个单独的线程中下载数据,该线程在完成后引发WebClient的DownloadDataCompleted事件.当我等待事件被调用时,我有一个循环:while(DateTime.Now <downloadStart.AddMinutes(timeout)&&!TestIsDone){}当调用事件时,DownloadDataCompleted事件将TestIsDone成员设置为true.这里的问题是如果代理设置不好,则永远不会调用Event,不会抛出异常,程序会在继续之前等待整个超时时间.以下是此方法的代码:
public static bool TestProxy(System.Net.WebProxy proxy)
{
ProxySettingsTestDone = false; //public static var
string address = //url to some arbitrary data on our server
System.Net.WebClient webClnt = new System.Net.WebClient();
webClnt.Proxy = proxy;
webClnt.Credentials = proxy.Credentials;
try
{
webClnt.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(DownloadDataCallback);
webClnt.DownloadDataAsync(new Uri(address));
//Timeout period
DateTime dnldStartTime = DateTime.Now;
while (DateTime.Now < dnldStartTime.AddMinutes(1.0) && !ProxySettingsTestDone)
{ }
if (!ProxySettingsTestDone) //Exceded timeout
{
throw new System.Net.WebException("Invalid Proxy Settings");
}
}
catch (System.Net.WebException e)
{
if (e.Status == System.Net.WebExceptionStatus.ProxyNameResolutionFailure)
{
//Proxy failed, server may or may not be there
Util.ConnectivityErrorMsg = e.Message;
return false;
}
else if (e.Status == System.Net.WebExceptionStatus.ProtocolError)
{
//File not found, server is down, but proxy settings succeded
ServerUp = false;
Util.ConnectivityErrorMsg = e.Message;
return true;
}
return false;
}
Util.ConnectivityErrorMsg = "";
return true;
}
private static void DownloadDataCallback(object sender, System.Net.DownloadDataCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
ProxySettingsTestDone = true;
else
throw new System.Net.WebException("Invalid Proxy Settings");
}
Run Code Online (Sandbox Code Playgroud)
抱歉这篇长篇文章.我想用测试这种新方法后发现的信息来更新这个问题.
谢谢,迈克
您可以在单独的线程中运行代理检查。如果线程花费的时间太长,则认为检查失败。
或者你可以使用 WebRequest,它允许你设置超时:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://url");
request.Proxy = proxy;
request.Timeout = 2000;
Run Code Online (Sandbox Code Playgroud)
如果请求在给定的超时时间内未完成,则将抛出WebException属性Status设置为 的异常。WebExceptionStatus.Timeout