lena和shane,家庭日志,xulavigne,Lena&Shane

如何实现

C# WebClient 无法设置超时时间的解决办法

2015-06-24 Shane Jhu

WebClient 无法设置请求超时时间,在执行请求时遇到网络不通等情况会很大几率造成app挂起。

我们可以从WebClient派生一个新的类,重载GetWebRequest方法。

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

/// <summary>
/// 为WebClient增加超时时间
/// <para>从WebClient派生一个新的类,重载GetWebRequest方法</para>
/// </summary>
public class NewWebClient : WebClient
{
    private int _timeout;

    /// <summary>
    /// 超时时间(毫秒)
    /// </summary>
    public int Timeout
    {
        get
        {
            return _timeout;
        }
        set
        {
            _timeout = value;
        }
    }

    public NewWebClient()
    {
        this._timeout = 60000;
    }

    public NewWebClient(int timeout)
    {
        this._timeout = timeout;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var result = base.GetWebRequest(address);
        result.Timeout = this._timeout;
        return result;
    }
}

使用与WebClient相同的调用方式调用建好的类,就可以设置超时时间:

NewWebClient myWebClient = new NewWebClient(30 * 60 * 1000);
byte[] myDataBuffer = myWebClient.DownloadData(url);
string result = Encoding.GetEncoding("GB2312").GetString(myDataBuffer);

测试可用,欢迎各位反馈。

本文由lenashane.com原创,转载请注明出处:查看原文

如果觉得文章还不错,请点个赞吧

7月 21 2022
宽恕不会改变过去,但是却可以拓展未来。

保罗·波希 (Paul Boese 美国商人、作家)