gpt4 book ai didi

c# - 如何在 WebClient.DownloadFileAsync 上实现超时

转载 作者:行者123 更新时间:2023-11-30 21:57:35 36 4
gpt4 key购买 nike

所以我认为 Webclient.DownloadFileAysnc 会有一个默认超时,但是查看文档我无法在任何地方找到任何关于它的信息,所以我猜它没有。

我正在尝试像这样从 Internet 下载文件:

 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;
}
}

但是如果我关闭我的 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;

否则创建你自己的weclient

  public class NewWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var req = base.GetWebRequest(address);
req.Timeout = 18000;
return req;
}
}

关于c# - 如何在 WebClient.DownloadFileAsync 上实现超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30618452/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com