c#网络客户端未超时
我正在尝试使用设置了超时的extended WebClient下载文件,但我遇到了超时问题(或者我认为应该导致超时的原因) 当我使用WebClient开始下载并收到一些数据,然后断开wifi连接时,我的程序将挂起下载,不会引发任何异常。我如何解决这个问题?c#网络客户端未超时,c#,timeout,webclient,C#,Timeout,Webclient,我正在尝试使用设置了超时的extended WebClient下载文件,但我遇到了超时问题(或者我认为应该导致超时的原因) 当我使用WebClient开始下载并收到一些数据,然后断开wifi连接时,我的程序将挂起下载,不会引发任何异常。我如何解决这个问题? 编辑:它实际上抛出异常,但比它应该的时间晚了很多(我设置了5分钟vs 1秒)——这就是我试图修复的 如果您发现我的代码有任何其他错误,请也告诉我。谢谢你的帮助 这是我的扩展类 class WebClientWithTimeout : WebC
编辑:它实际上抛出异常,但比它应该的时间晚了很多(我设置了5分钟vs 1秒)——这就是我试图修复的 如果您发现我的代码有任何其他错误,请也告诉我。谢谢你的帮助 这是我的扩展类
class WebClientWithTimeout : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest w = base.GetWebRequest(address);
w.Timeout = 1000;
return w;
}
}
这是下载
using (WebClientWithTimeout wct = new WebClientWithTimeout())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
wct.DownloadFile("https://example.com", file);
}
catch (Exception e)
{
Console.WriteLine("Download: {0} failed with exception:{1} {2}", file, Environment.NewLine, e);
}
}
试试这个,你可以通过这个避免UI阻塞。当设备连接到WiFi时,WiFi将继续下载
//declare globally
DateTime lastDownloaded = DateTime.Now;
Timer t = new Timer();
WebClient wc = new WebClient();
//Declare无论您在何处启动下载我的案例按钮单击
private void button1_Click(object sender, EventArgs e)
{
wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
lastDownloaded = DateTime.Now;
t.Interval = 1000;
t.Tick += T_Tick;
wc.DownloadFileAsync(new Uri("https://github.com/google/google-api-dotnet-client/archive/master.zip"), @"C:\Users\chkri\AppData\Local\Temp\master.zip");
}
private void T_Tick(object sender, EventArgs e)
{
if ((DateTime.Now - lastDownloaded).TotalMilliseconds > 1000)
{
wc.CancelAsync();
}
}
private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
lblProgress.Text = e.Error.Message;
}
}
private void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
lastDownloaded = DateTime.Now;
lblProgress.Text = e.BytesReceived + "/" + e.TotalBytesToReceive;
}
你需要异步下载来保持UI的活跃。程序没有UI,所以我并不介意它是同步的。让我烦恼的是,如果网络上发生了什么事情,文件无法下载,那么下载就不会超时。好的,知道了,请看我的答案。也许你可以实现异步调用,并决定何时取消请求。如果不取消下载,可以花点时间检查是否有下载进度