如何更改.NET WebClient对象的超时

Rya*_*all 217 .net c# webclient file download

我试图将客户端的数据下载到我的本地机器(以编程方式),并且他们的网络服务器非常非常慢,导致我的WebClient对象超时.

这是我的代码:

WebClient webClient = new WebClient();

webClient.Encoding = Encoding.UTF8;
webClient.DownloadFile(downloadUrl, downloadFile);
Run Code Online (Sandbox Code Playgroud)

有没有办法在这个对象上设置无限超时?或者,如果没有,任何人都可以用另一种方式帮助我做一个例子吗?

该URL在浏览器中正常工作 - 只需3分钟即可显示.

kis*_*isp 367

您可以延长超时:继承原始WebClient类并覆盖webrequest getter以设置自己的超时,如下例所示.

在我的案例中,MyWebClient是一个私有类:

private class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest w = base.GetWebRequest(uri);
        w.Timeout = 20 * 60 * 1000;
        return w;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 该类的名称应为:PatientWebClient;) (73认同)
  • 默认超时为100秒.虽然它似乎运行了30秒. (22认同)
  • @webwires一个人应该使用`.TotalMilliseconds`而不是`.Milliseconds`! (15认同)
  • 什么是默认超时? (5认同)
  • http://stackoverflow.com/questions/601861/set-timeout-for-webclient-downloadfile (4认同)
  • 使用Timespan TimeSpan.FromSeconds(20)设置Timeout更容易.Milliseconds ...虽然很棒的解决方案! (2认同)

小智 24

第一个解决方案对我不起作用,但这里有一些代码对我有用.

    private class WebClient : System.Net.WebClient
    {
        public int Timeout { get; set; }

        protected override WebRequest GetWebRequest(Uri uri)
        {
            WebRequest lWebRequest = base.GetWebRequest(uri);
            lWebRequest.Timeout = Timeout;
            ((HttpWebRequest)lWebRequest).ReadWriteTimeout = Timeout;
            return lWebRequest;
        }
    }

    private string GetRequest(string aURL)
    {
        using (var lWebClient = new WebClient())
        {
            lWebClient.Timeout = 600 * 60 * 1000;
            return lWebClient.DownloadString(aURL);
        }
    }
Run Code Online (Sandbox Code Playgroud)


Fen*_*ton 20

您需要使用HttpWebRequest而不是WebClientWebClient不扩展超时的情况下设置超时(即使它使用了HttpWebRequest).使用HttpWebRequest替代将允许您设置超时.

  • "System.Net.HttpWebRequest.HttpWebRequest()'已过时:'此API支持.NET Framework基础结构,不能直接在您的代码中使用" (7认同)
  • @usefulBee - 因为你不应该调用那个构造函数:`"不要使用HttpWebRequest构造函数.使用WebRequest.Create方法初始化新的HttpWebRequest对象."来自https://msdn.microsoft.com/en-us/库/ system.net.httpwebrequest(v = vs.110)的.aspx.另请参阅http://stackoverflow.com/questions/400565/is-there-any-way-to-inherit-a-class-without-constructors-in-net (3认同)

小智 10

拔出网线时无法使w.Timeout代码工作,它只是没有超时,转移到使用HttpWebRequest并立即完成工作.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downloadUrl);
request.Timeout = 10000;
request.ReadWriteTimeout = 10000;
var wresp = (HttpWebResponse)request.GetResponse();

using (Stream file = File.OpenWrite(downloadFile))
{
    wresp.GetResponseStream().CopyTo(file);
}
Run Code Online (Sandbox Code Playgroud)


Gle*_*nnG 9

为了完整起见,这里的kisp解决方案移植到VB(无法在注释中添加代码)

Namespace Utils

''' <summary>
''' Subclass of WebClient to provide access to the timeout property
''' </summary>
Public Class WebClient
    Inherits System.Net.WebClient

    Private _TimeoutMS As Integer = 0

    Public Sub New()
        MyBase.New()
    End Sub
    Public Sub New(ByVal TimeoutMS As Integer)
        MyBase.New()
        _TimeoutMS = TimeoutMS
    End Sub
    ''' <summary>
    ''' Set the web call timeout in Milliseconds
    ''' </summary>
    ''' <value></value>
    Public WriteOnly Property setTimeout() As Integer
        Set(ByVal value As Integer)
            _TimeoutMS = value
        End Set
    End Property


    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
        If _TimeoutMS <> 0 Then
            w.Timeout = _TimeoutMS
        End If
        Return w
    End Function

End Class

End Namespace
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 9

对于需要适用于异步/任务方法的超时 WebClient 的任何人,建议的解决方案将不起作用。这是有效的方法:

public class WebClientWithTimeout : WebClient
{
    //10 secs default
    public int Timeout { get; set; } = 10000;

    //for sync requests
    protected override WebRequest GetWebRequest(Uri uri)
    {
        var w = base.GetWebRequest(uri);
        w.Timeout = Timeout; //10 seconds timeout
        return w;
    }

    //the above will not work for async requests :(
    //let's create a workaround by hiding the method
    //and creating our own version of DownloadStringTaskAsync
    public new async Task<string> DownloadStringTaskAsync(Uri address)
    {
        var t = base.DownloadStringTaskAsync(address);
        if(await Task.WhenAny(t, Task.Delay(Timeout)) != t) //time out!
        {
            CancelAsync();
        }
        return await t;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里写了关于完整解决方法的博客


dar*_*iom 7

正如Sohnee所说,使用System.Net.HttpWebRequest和设置Timeout属性而不是使用System.Net.WebClient.

但是,您无法设置无限超时值(它不受支持,尝试这样做会抛出ArgumentOutOfRangeException).

我建议首先执行HEAD HTTP请求并检查Content-Length返回的标头值以确定您正在下载的文件中的字节数,然后相应地为后续GET请求设置超时值,或者只是指定一个非常长的超时值永远不会超过.


Jos*_*osh 7

'CORRECTED VERSION OF LAST FUNCTION IN VISUAL BASIC BY GLENNG

Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
            Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
            If _TimeoutMS <> 0 Then
                w.Timeout = _TimeoutMS
            End If
            Return w  '<<< NOTICE: MyBase.GetWebRequest(address) DOES NOT WORK >>>
        End Function
Run Code Online (Sandbox Code Playgroud)


Kon*_* S. 6

用法:

using (var client = new TimeoutWebClient(TimeSpan.FromSeconds(10)))
{
    return await client.DownloadStringTaskAsync(url).ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)

班级:

using System;
using System.Net;

namespace Utilities
{
    public class TimeoutWebClient : WebClient
    {
        public TimeSpan Timeout { get; set; }

        public TimeoutWebClient(TimeSpan timeout)
        {
            Timeout = timeout;
        }

        protected override WebRequest GetWebRequest(Uri uri)
        {
            var request = base.GetWebRequest(uri);
            if (request == null)
            {
                return null;
            }

            var timeoutInMilliseconds = (int) Timeout.TotalMilliseconds;

            request.Timeout = timeoutInMilliseconds;
            if (request is HttpWebRequest httpWebRequest)
            {
                httpWebRequest.ReadWriteTimeout = timeoutInMilliseconds;
            }

            return request;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我推荐一个更现代的解决方案:

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

public static async Task<string> ReadGetRequestDataAsync(Uri uri, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
{
    using var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
    if (timeout != null)
    {
        source.CancelAfter(timeout.Value);
    }

    using var client = new HttpClient();
    using var response = await client.GetAsync(uri, source.Token).ConfigureAwait(false);

    return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)

它会OperationCanceledException在超时后抛出一个。