How to use HttpWebRequest (.NET) asynchronously?

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

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

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 14:33

    .NET has changed since many of these answers were posted, and I'd like to provide a more up-to-date answer. Use an async method to start a Task that will run on a background thread:

    private async Task MakeRequestAsync(String url)
    {    
        String responseText = await Task.Run(() =>
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                WebResponse response = request.GetResponse();            
                Stream responseStream = response.GetResponseStream();
                return new StreamReader(responseStream).ReadToEnd();            
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            return null;
        });
    
        return responseText;
    }
    

    To use the async method:

    String response = await MakeRequestAsync("http://example.com/");
    

    Update:

    This solution does not work for UWP apps which use WebRequest.GetResponseAsync() instead of WebRequest.GetResponse(), and it does not call the Dispose() methods where appropriate. @dragansr has a good alternative solution that addresses these issues.

提交回复
热议问题