Search code examples
c#.netasynchronoushttprequest

How to use HttpWebRequest (.NET) asynchronously?


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


Solution

  • 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.