【问题标题】:How to set Timeout in HttpWebResponse C# Windows Form如何在 HttpWebResponse C# Windows 窗体中设置超时
【发布时间】:2016-06-13 08:25:07
【问题描述】:

目前我有这个代码:

    public bool checkIfDown(string URL)
    {
        try
        {
            //Creating the HttpWebRequest
            HttpWebRequest request = WebRequest.Create("http://www." + URL) as HttpWebRequest;
            //Setting the Request method HEAD, you can also use GET too.
            request.Method = "HEAD";
            request.Timeout = 1000;
            //Getting the Web Response.
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //Returns TRUE if the Status code == 200                
            return (response.StatusCode == HttpStatusCode.OK);
        }
        catch
        {
            //Any exception will returns false.
            return false;
        }
    }

它检查域是否Up/Down,但我的问题是响应通常需要超过 10 秒才能进入 catch 部分。

例如我的string domain是sample123121212.com,该函数应该返回false,但耗时超过10秒。

我想要在更短的时间内至少 2 秒返回 false,因为我需要处理 至少 100 domains

关于如何做到这一点的任何建议?

【问题讨论】:

    标签: c# winforms http


    【解决方案1】:

    根据this的回答,将Proxy属性设置为null可以显着减少响应时间。

    尝试以下方法:

    request.Proxy = null;
    

    在致电GetResponse()之前

    此外,您可以将属性 ReadWriteTimeout 设置为特定值(2000 毫秒?),以确保您可以限制读取和写入流所需的时间。

    【讨论】:

    【解决方案2】:

    我使用的方法来自this

      using System.Threading.Tasks;
    
      var task = Task.Run(() => SomeMethod(input));
      if (task.Wait(TimeSpan.FromSeconds(10)))
         return task.Result;
      else
         throw new Exception("Timed out");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 2015-01-07
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      相关资源
      最近更新 更多