Direct return after asynchronous timeout, direct return after asynchronous timeout

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.