设置 webClient.DownloadFile()的超时

我正在使用 webClient.DownloadFile()下载一个文件,我可以设置一个超时,以便它不会采取这么长的时间,如果它不能访问该文件?

110464 次浏览

Try WebClient.DownloadFileAsync(). You can call CancelAsync() by timer with your own timeout.

My answer comes from here

You can make a derived class, which will set the timeout property of the base WebRequest class:

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

and you can use it just like the base WebClient class.

Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:

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

Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.

A lot of people make use of using(...) for the WebClient. Yes, WebClient implements IDisposable but this can cause socket exhaustion if you do it in bulk: https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/