我试图下载一个客户端的数据到我的本地机器(编程),他们的web服务器非常非常慢,这导致我的WebClient对象超时。
这是我的代码:
WebClient webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
webClient.DownloadFile(downloadUrl, downloadFile);
有没有办法在这个对象上设置无限超时?如果不是,有没有人能帮我举个例子告诉我另一种方法?
该URL在浏览器中工作正常-只需要大约3分钟就能显示出来。
根据kisp解决方案,这是我的编辑版本工作异步:
类WebConnection.cs
internal class WebConnection : WebClient
{
internal int Timeout { get; set; }
protected override WebRequest GetWebRequest(Uri Address)
{
WebRequest WebReq = base.GetWebRequest(Address);
WebReq.Timeout = Timeout * 1000 // Seconds
return WebReq;
}
}
异步任务
private async Task GetDataAsyncWithTimeout()
{
await Task.Run(() =>
{
using (WebConnection webClient = new WebConnection())
{
webClient.Timeout = 5; // Five seconds (the multiplication is in the override)
webClient.DownloadData("https://www.yourwebsite.com");
}
});
} // await GetDataAsyncWithTimeout()
否则,如果你不想使用async:
private void GetDataSyncWithTimeout()
{
using (WebConnection webClient = new WebConnection())
{
webClient.Timeout = 5; // Five seconds (the multiplication is in the override)
webClient.DownloadData("https://www.yourwebsite.com");
}
} // GetDataSyncWithTimeout()
根据kisp解决方案,这是我的编辑版本工作异步:
类WebConnection.cs
internal class WebConnection : WebClient
{
internal int Timeout { get; set; }
protected override WebRequest GetWebRequest(Uri Address)
{
WebRequest WebReq = base.GetWebRequest(Address);
WebReq.Timeout = Timeout * 1000 // Seconds
return WebReq;
}
}
异步任务
private async Task GetDataAsyncWithTimeout()
{
await Task.Run(() =>
{
using (WebConnection webClient = new WebConnection())
{
webClient.Timeout = 5; // Five seconds (the multiplication is in the override)
webClient.DownloadData("https://www.yourwebsite.com");
}
});
} // await GetDataAsyncWithTimeout()
否则,如果你不想使用async:
private void GetDataSyncWithTimeout()
{
using (WebConnection webClient = new WebConnection())
{
webClient.Timeout = 5; // Five seconds (the multiplication is in the override)
webClient.DownloadData("https://www.yourwebsite.com");
}
} // GetDataSyncWithTimeout()