classProgram {Static voidMain (string[] args) { varresult = Downloadstringwithtimeout ("http://www.yueyangdujia.com"); Console.WriteLine ("Asynchronous Method Execution"); for(inti =0; I <3; i++) {System.Threading.Thread.Sleep ( +); Console.WriteLine ("Take a break."+ (i+1)+"seconds"); } varstr= result. Result;//this uses the return value of the Async method and waits for the asynchronous method to execute. Console.WriteLine ("after the Async method executes, the following code is executed synchronously"); Console.WriteLine (str); Console.read (); } Static Asynctask<string> Downloadstringwithtimeout (stringURI) { using(varClient=NewHttpClient ()) { varDownloadtask =client. Getstringasync (URI); varTimeouttask = Task.delay ( the); varCompletedtask =awaitTask.whenany (Downloadtask, Timeouttask); if(Completedtask = =timeouttask) {System.Threading.Thread.Sleep ( -); Console.WriteLine ("asynchronous method Execution Complete"); return NULL; } System.Threading.Thread.Sleep ( -); Console.WriteLine ("asynchronous method Execution Complete"); return awaitDownloadtask; } } }
The execution order is shown as Console.WriteLine. The downloadstringwithtimeout is executed with the following code, approximately 2 seconds. var str= result. Result; The asynchronous method will wait for the async method to execute when it calls the return value.
Down to remove some code as follows:
classProgram {Static voidMain (string[] args) { varresult = Downloadstringwithtimeout ("http://www.yueyangdujia.com"); varstr= result. Result;//this uses the return value of the Async method and waits for the asynchronous method to execute. Console.WriteLine (str); Console.read (); } Static Asynctask<string> Downloadstringwithtimeout (stringURI) { using(varClient=NewHttpClient ()) { varDownloadtask =client. Getstringasync (URI); varTimeouttask = Task.delay ( the); varCompletedtask =awaitTask.whenany (Downloadtask, Timeouttask); if(Completedtask = =timeouttask) { return NULL; } return awaitDownloadtask; } } }
Whenany accepts two async method parameters to return the first executed method. The above can adjust the parameters of the Task.delay. Returns null if it is small enough.
C # Asynchronous Programming (i): Asynchronous basics