How to use HttpWebRequest (.NET) asynchronously?

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

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

8条回答
  •  鱼传尺愫
    2020-11-22 14:43

    By far the easiest way is by using TaskFactory.FromAsync from the TPL. It's literally a couple of lines of code when used in conjunction with the new async/await keywords:

    var request = WebRequest.Create("http://www.stackoverflow.com");
    var response = (HttpWebResponse) await Task.Factory
        .FromAsync(request.BeginGetResponse,
                                request.EndGetResponse,
                                null);
    Debug.Assert(response.StatusCode == HttpStatusCode.OK);
    

    If you can't use the C#5 compiler then the above can be accomplished using the Task.ContinueWith method:

    Task.Factory.FromAsync(request.BeginGetResponse,
                                        request.EndGetResponse,
                                        null)
        .ContinueWith(task =>
        {
            var response = (HttpWebResponse) task.Result;
            Debug.Assert(response.StatusCode == HttpStatusCode.OK);
        });
    

提交回复
热议问题