Jonas m
Jonas m

Reputation: 2734

Delaying while loop doing HttpRequest in c#

I'm doing some HTTP header testing to check if a url is alive or not. Im doing this with random generated string urls going through a while loop which calls the HttpRequest function. The problem is that as long as HttpWebRequest is Async the while loop keeps running taking alot of processes checking hell of alot links at the same time. So what i would like to do is ti delay the while loop for either some seconds/milliseconds or simply wait for the HttpWebRequest to only handle like 3 requests at a time. Im just lost here and i dont know how to do so.

My while loop looks like this

 String Episode = textBox1.Text;
            String Rand = newInt(16);
            String Url = "http://someurl.com?_" + Episode + "paradisehotel_" + Rand + ".wmv";

            while (checkUrl(Url) == false)
            {
                Rand = newInt(16);
                while (isInList(Rand, list))
                {
                    Rand = newInt(16);
                }

                list.Add(Rand);

                Url = "someurl.com_" + Episode + "paradisehotel_" + Rand + ".wmv";
            }

My CheckUrl function looks like this

private bool checkUrl(String url)
{

    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@url);
    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
    try
    {
        WebResponse response = req.GetResponse();
        return true;
    }
    catch (WebException ex)
    {
        Console.WriteLine(ex.Message);
        return false;
    }

}

I hope someone way more clever than me has a solution. Thank you mostly Jonas

Upvotes: 1

Views: 1864

Answers (1)

AaronHS
AaronHS

Reputation: 1352

Take the example here (too much code to copy and paste it all here), which uses an async callback, and increment a static counter inside the callback, after you have loaded the response. Then all you need to do is check the counter isn't over a max value in each iteration of the while loop prior to executing the next request, by using a thread.sleep.

Upvotes: 1

Related Questions