om471987
om471987

Reputation: 5637

Why HTTPWebRespnse takes longer even if HTTPWebRequest is sent long time back?

Hola check this code.

     var watch = new Stopwatch();
     watch.Start();
     var request = HttpWebRequest.Create(new Uri("http://localhost:59449/stwebapi/chat?userId=john")) as HttpWebRequest;
     Console.WriteLine(watch.Elapsed);

     Thread.Sleep(5000);

     watch.Restart();
     var response = request.GetResponse();
     Console.WriteLine(watch.Elapsed);

I sent web request, waited for a long time and then got the response. Still response took longer to execute. The result I got was

00:00:00.1142339
00:00:03.1365544

Why response took me 3 seconds? Same response lag is there with asynchronous response.

I want GetResponse function to be executed immediately. How can I achieve that?

Thanks.

Upvotes: 0

Views: 722

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503469

I strongly suspect that until you call GetResponse, the request isn't even sent... so your Thread.Sleep is basically doing you no good at all.

Why don't you just call GetResponse immediately? If it takes 3 seconds, then presumably that's how long the web server took to answer your request...

(As an aside, you should be using a using statement to make sure you dispose of the WebResponse; otherwise you'll end up with requests timing out as the connection pool waits for a connection to become available.)

Upvotes: 4

Related Questions