webclient 的 DownloadDataAsync异常捕获问题 请大家帮忙看看 先感谢
这个函数是获取公网 IP地址的。异常捕捉不到,比如我把网卡禁用,执行上面代码,出现系统崩溃的那种异常提示。 这个地方到底如何捕获异常啊
public string GetExternalIP()
{
string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp";
WebClient wc = new WebClient();
UTF8Encoding utf8 = new UTF8Encoding();
try
{
string ipaddr = null;
bool done = false;
wc.DownloadDataCompleted += new
DownloadDataCompletedEventHandler((object sender,
DownloadDataCompletedEventArgs e) =>
{
ipaddr = utf8.GetString(e.Result);
done = true;
});
wc.DownloadDataAsync(new Uri(whatIsMyIp));
return ipaddr;
}
catch
{
return null;
}
finally
{
if (wc != null)
{
wc.Dispose();
wc = null;
}
}
}
public string GetExternalIP()
{
string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp";
WebClient wc = new WebClient();
UTF8Encoding utf8 = new UTF8Encoding();
try
{
string ipaddr = null;
bool done = false;
wc.DownloadDataCompleted += new
DownloadDataCompletedEventHandler((object sender,
DownloadDataCompletedEventArgs e) =>
{
ipaddr = utf8.GetString(e.Result);
done = true;
});
wc.DownloadDataAsync(new Uri(whatIsMyIp));
return ipaddr;
}
catch
{
return null;
}
finally
{
if (wc != null)
{
wc.Dispose();
wc = null;
}
}
}
...全文
相关推荐
WebClient下载文件展示进度条
请注意,实际应用中可能需要处理错误和异常,以及考虑线程同步问题,确保UI线程安全地更新进度条。
C#多线程下载文件源码
在多线程环境下,我们需要为每个线程创建一个独立的WebClient或HttpClient实例,以避免并发访问同一资源时可能出现的问题。线程间的同步也是非常关键的一环。
winform 中显示异步下载的图片
**异常处理**:在实际应用中,还需要考虑异常处理,例如网络问题、资源不可用等。
向客户端代码公开异步功能:Windows Phone 7
的DownloadDataAsync方法启动异步下载 WebClient client = new WebClient(); client.DownloadDataCompleted += (sender
winform实现多线程下载
**错误处理**:确保对可能出现的异常进行捕获和处理,例如网络中断、权限问题等。8. **优化与性能调优**:根据实际需求调整线程数量,过多的线程可能会增加系统开销,而过少可能无法充分利用网络带宽。


