How to use HttpWebRequest (.NET) asynchronously?

后端 未结 8 1721
天涯浪人
天涯浪人 2020-11-22 13:56

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

8条回答
  •  猫巷女王i
    2020-11-22 14:24

    Everyone so far has been wrong, because BeginGetResponse() does some work on the current thread. From the documentation:

    The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection, and TCP socket connection, for example) before this method becomes asynchronous. As a result, this method should never be called on a user interface (UI) thread because it might take considerable time (up to several minutes depending on network settings) to complete the initial synchronous setup tasks before an exception for an error is thrown or the method succeeds.

    So to do this right:

    void DoWithResponse(HttpWebRequest request, Action responseAction)
    {
        Action wrapperAction = () =>
        {
            request.BeginGetResponse(new AsyncCallback((iar) =>
            {
                var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);
                responseAction(response);
            }), request);
        };
        wrapperAction.BeginInvoke(new AsyncCallback((iar) =>
        {
            var action = (Action)iar.AsyncState;
            action.EndInvoke(iar);
        }), wrapperAction);
    }
    

    You can then do what you need to with the response. For example:

    HttpWebRequest request;
    // init your request...then:
    DoWithResponse(request, (response) => {
        var body = new StreamReader(response.GetResponseStream()).ReadToEnd();
        Console.Write(body);
    });
    

提交回复
热议问题