應用場景
異步同時請求多個地址,獲得返回的信息並輸出,排除時間響應太久的以免造成不必要的時間等待。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 TaskTest(); 6 Console.ReadLine(); 7 } 8 9 static async void ddd() 10 { 11 Stopwatch sw = new Stopwatch(); 12 sw.Start(); 13 List<string> urls = new List<string>() { "http://www.baidu.com", "http://www.360.com" }; 14 string a = await DownloadAllAsync(urls); 15 16 Console.WriteLine(a); 17 sw.Stop(); 18 Console.WriteLine(sw.ElapsedMilliseconds); 19 Console.ReadLine(); 20 } 21 static HttpClient httpClient = new HttpClient(); 22 static async Task<string> DownloadAllAsync(IEnumerable<string> urls) 23 { 24 25 var downloads = urls.Select(url => httpClient.GetStringAsync(url)); 26 Task<string>[] downloadTasks = downloads.ToArray(); 27 28 string[] pages = await Task.WhenAll(downloadTasks); 29 30 return string.Concat(pages); 31 } 32 33 static void TaskTest() 34 { 35 var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(2000)); 36 Task<string> t1 = GetString("http://www.baidu.com"); 37 Task<string> t2 = GetString("http://www.360.com"); 38 Task<string> t3 = GetString("http://www.github.com"); 39 40 Task<string>[] arr = new Task<string>[] { t1, t2, t3 }; 41 Task.WaitAll(arr,2000); 42 foreach (var dd in arr) 43 Console.WriteLine(dd.Result.ToString()); 44 } 45 46 static async Task<string> GetString(string str) 47 { 48 return await httpClient.GetStringAsync(str); 49 50 } View Code
源碼