【发布时间】:2010-03-25 18:40:25
【问题描述】:
我正在处理的程序中的互联网连接有很多问题,这一切似乎都是由于代理设置的一些问题造成的。此时大部分问题都已修复,但我现在遇到的问题是我测试代理设置的方法使一些用户等待很长时间。
这是我的工作:
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
}
这是我发现测试代理设置是否正确的唯一方法。我尝试对我们的 Web 服务进行 Web 服务调用,但在调用时不需要代理设置。即使我有虚假的代理设置,它也会起作用。但是,上面的方法没有我可以设置的超时成员,我可以使用 DownloadData 而不是 DownloadDataAsync 因为我需要等到方法完成,以便在继续之前知道设置是否正确在程序中打开。
感谢任何有关更好方法或解决此方法的建议。
迈克
编辑:我尝试了其他方法,但没有运气。我使用 DownloadDataAsync 方法在一个单独的线程中下载数据,该线程在完成时会引发 WebClient 的 DownloadDataCompleted 事件。当我等待事件被调用时,我有一个循环: while(DateTime.Now
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");
}
抱歉,帖子太长了。我想用测试这种新方法后发现的信息来更新这个问题。
谢谢, 迈克
【问题讨论】: