This article describes the method of implementing asynchronous GET in C#. Share it for your reference. The specific implementation method is as follows:
using System; using ; using ; using ; using ; using ; using ; using ; namespace WebClientAsynProject { public class Program { #region HttpWebRequest Asynchronous GET public static void AsyncGetWithWebRequest(string url) { var request = (HttpWebRequest) (new Uri(url)); (new AsyncCallback(ReadCallback), request); } private static void ReadCallback(IAsyncResult asynchronousResult) { var request = (HttpWebRequest) ; var response = (HttpWebResponse) (asynchronousResult); using (var streamReader = new StreamReader(())) { var resultString = (); (resultString); } } #endregion #region WebClientAsync GET public static void AsyncGetWithWebClient(string url) { var webClient = new WebClient(); += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); (new Uri(url)); } private static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { //(); ( != null ? "An error occurred with WebClient asynchronous GET!" : ); } #endregion #region WebClient's OpenReadAsync test public static void TestGetWebResponseAsync(string url) { var webClient = new WebClient(); += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted); (new Uri(url)); } private static void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if( == null) { var streamReader = new StreamReader(); var result = (); (result); } else { ("An error occurred when executing OpenReadAsync for WebClient:" + ); } } #endregion public static void Main(string[] args) { AsyncGetWithWebRequest(""); ("hello"); AsyncGetWithWebClient(""); ("world"); TestGetWebResponseAsync(""); ("jxqlovejava"); (); } } }
I hope this article will be helpful to everyone's C# programming.