2016-06-13 68 views
1

目前我有这样的代码:如何设置超时在HttpWebResponse C#Windows窗体

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

,检查域是否向上/向下,但我的问题是,反应通常需要超过10秒进入捕捉部分。

例如我的string domain是sample123121212.com,该函数应该返回false,但它花费了10秒以上。

我想是在很短的时间返回false至少2个秒钟,因为我需要处理ATLEAST100 domains

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

回答

0

我使用的方法是从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"); 
1

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

尝试以下方法:(?2000毫秒)

request.Proxy = null; 

调用GetResponse()

而且之前,你可以设置属性ReadWriteTimeout到一个特定的值,以确保您可以限制读取所需的时间和写入流。

+0

遗憾地说,但它不会改变的结果:( – jt25

+1

我打算使用http://stackoverflow.com/questions/13513650/how-to-set-timeout-for-a- line-of-c-sharp-code – jt25

+0

@AJB使用任务是一种有趣的方法 – Alex

相关问题