C# 5.0后,我们可以简单的使用 async/await 关键字 进行实现异步操作
同步操作:
public string Test() { DateTime startTime = DateTime.Now; string api_1s = "http://localhost:58575/home/Api_1s"; string api_3s = "http://localhost:58575/home/Api_3s"; string api_5s = "http://localhost:58575/home/Api_5s"; GetRequest(api_1s); GetRequest(api_3s); GetRequest(api_5s); DateTime endTime = DateTime.Now; return "响应时间:" + (endTime - startTime).TotalSeconds.ToString() + "s"; //9.1s }
异步操作:
using System.Threading.Tasks; public async Task< string > TestAsync() { DateTime startTime = DateTime.Now; string api_1s = "http://localhost:58575/home/Api_1s"; string api_3s = "http://localhost:58575/home/Api_3s"; string api_5s = "http://localhost:58575/home/Api_5s"; Listtasks = new List (); var t1 = GetRequestAsync(api_1s); var t2 = GetRequestAsync(api_3s); var t3 = GetRequestAsync(api_5s); tasks.Add(t1); tasks.Add(t2); tasks.Add(t3); await Task.WhenAll(tasks); DateTime endTime = DateTime.Now; return "响应时间:" + (endTime - startTime).TotalSeconds.ToString() + "s";//5.1s }
其中请求方法如下:
public async TaskGetRequestAsync(string url) { WebClient MyWebClient = new WebClient(); MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据 Byte[] pageData = await MyWebClient.DownloadDataTaskAsync(url); //从指定网站下载数据 return Encoding.UTF8.GetString(pageData); } public string GetRequest(string url) { WebClient MyWebClient = new WebClient(); MyWebClient.Credentials = CredentialCache.DefaultCredentials; Byte[] pageData = MyWebClient.DownloadData(url); return Encoding.UTF8.GetString(pageData); }