Answers:
尝试WebClient.DownloadFileAsync()
。您可以CancelAsync()
使用自己的超时计时器进行呼叫。
var taskDownload = client.DownloadFileTaskAsync(new Uri("http://localhost/folder"),"filename")
然后taskDownload.Wait(TimeSpan.FromSeconds(5));
我的答案来自这里
您可以创建派生类,这将设置基WebRequest
类的timeout属性:
using System;
using System.Net;
public class WebDownload : WebClient
{
/// <summary>
/// Time in milliseconds
/// </summary>
public int Timeout { get; set; }
public WebDownload() : this(60000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}
您可以像基本的WebClient类一样使用它。
request.Timeout
。错误消息'System.Net.WebRequest' does not contain a definition for 'Timeout' and no extension method 'Timeout' accepting a first argument of type 'System.Net.WebRequest' could be found (are you missing a using directive or an assembly reference?)
,我缺少什么?
using
了此代码段所使用的指令。
假设您想同步执行此操作,则使用WebClient.OpenRead(...)方法并在返回的Stream上设置超时将为您提供所需的结果:
using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
if (stream != null)
{
stream.ReadTimeout = Timeout.Infinite;
using (var reader = new StreamReader(stream, Encoding.UTF8, false))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line != String.Empty)
{
Console.WriteLine("Count {0}", count++);
}
Console.WriteLine(line);
}
}
}
}
从WebClient派生并重写GetWebRequest(...)以设置@Beniamin建议的超时,对我来说不起作用,但确实如此。
stream.ReadTimeout
大于执行请求的实际花费,我仍然会收到WebException说的“请求已被中止-操作已超时”