use*_*er1 3 c# timeout webclient .net-4.0
所以我认为Webclient.DownloadFileAysnc会有一个默认超时,但查看文档我在任何地方都找不到任何有关它的信息,所以我猜它没有。
我正在尝试从互联网下载文件,如下所示:
using (WebClient wc = new WebClient())
{
wc.DownloadProgressChanged += ((sender, args) =>
{
IndividualProgress = args.ProgressPercentage;
});
wc.DownloadFileCompleted += ((sender, args) =>
{
if (args.Error == null)
{
if (!args.Cancelled)
{
File.Move(filePath, Path.ChangeExtension(filePath, ".jpg"));
}
mr.Set();
}
else
{
ex = args.Error;
mr.Set();
}
});
wc.DownloadFileAsync(new Uri("MyInternetFile", filePath);
mr.WaitOne();
if (ex != null)
{
throw ex;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我关闭 WiFi(模拟互联网连接中断),我的应用程序就会暂停并且下载停止,但它永远不会向该方法报告这一情况DownloadFileCompleted。
因此,我想在我的WebClient.DownloadFileAsync方法上实现超时。这可能吗?
顺便说一句,我正在使用 .Net 4 并且不想添加对第三方库的引用,因此无法使用Async/Await关键字
您可以使用 WebClient.DownloadFileAsync()。现在,在计时器内,您可以像这样调用 CancelAsync() :
System.Timers.Timer aTimer = new System.Timers.Timer();
System.Timers.ElapsedEventHandler handler = null;
handler = ((sender, args)
=>
{
aTimer.Elapsed -= handler;
wc.CancelAsync();
});
aTimer.Elapsed += handler;
aTimer.Interval = 100000;
aTimer.Enabled = true;
Run Code Online (Sandbox Code Playgroud)
否则创建您自己的微客户端
public class NewWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var req = base.GetWebRequest(address);
req.Timeout = 18000;
return req;
}
}
Run Code Online (Sandbox Code Playgroud)