R – Stopping an Async HttpWebRequest

asynchronoushttpwebrequestnet

I have an application that makes several concurrent requests to a web resource using HttpWebRequest asynchronously. Even though I've set the timeout property of my HttpWebRequest instance to say 5 seconds, sometimes when async calling BeginGetRequestStream, getting the stream can take much longer than that and is causing quote a mess for me. Is there a way to limit the amount of time that can be had for it to request the stream? Also, if I get the stream and decide I want to abandon the request entirely there by never actually calling BeginGetResponse, are there any ramifications to that course of action?

Best Answer

you can use this

ManualResetEvent allDone = new ManualResetEvent(false);
bool isRequestFnishedInCorrectTime=allDone.WaitOne(5000);
if(isRequestFnishedInCorrectTime==false)
    request.Abort();
else
    //request success

the important point here after get response you have to set this:

allDone.Set();

if request can't finish in 5 seconds request will abort.