ajbee
ajbee

Reputation: 3641

How to set Timeout in HttpWebResponse C# Windows Form

Currently I have this code:

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

which checks whether a Domain is Up/Down, but my problem is that the response usually take more than 10 secs to go in catch section.

For example my string domain is sample123121212.com, the function should return false but it took more than 10 secs.

What I want is to return false in much shorter time atleast 2 secs, because I need to process atleast 100 domains.

Any suggestion on how to do this?

Upvotes: 1

Views: 1412

Answers (2)

ajbee
ajbee

Reputation: 3641

The approach that I used was from 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");

Upvotes: 0

Alex
Alex

Reputation: 987

According to this answer, setting the property Proxy to null can significantly reduce the response time.

Try the following:

request.Proxy = null;

before calling GetResponse()

Also, you can set the Property ReadWriteTimeout to a particular value (2000 ms?) to ensure you can limit the time required to read and write to the stream.

Upvotes: 1

Related Questions