How to use HttpWebRequest (.NET) asynchronously?

Jason picture Jason · Oct 14, 2008 · Viewed 178.1k times · Source

How can I use HttpWebRequest (.NET, C#) asynchronously?

Answer

Jon B picture Jon B · Oct 14, 2008

Use HttpWebRequest.BeginGetResponse()

HttpWebRequest webRequest;

void StartWebRequest()
{
    webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}

void FinishWebRequest(IAsyncResult result)
{
    webRequest.EndGetResponse(result);
}

The callback function is called when the asynchronous operation is complete. You need to at least call EndGetResponse() from this function.