Direct return after asynchronous timeout, direct return after asynchronous timeout
Application scenarios
Requests multiple addresses asynchronously at the same time to obtain the returned information and output it. If the response time is too long, the unnecessary wait time is avoided.
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
Source code