1. Await
For example, there is a static method m, to call this method asynchronously in the program, the keyword await before this method, then when the program runs to this statement, it will immediately return the method containing the statement, and execute the M method asynchronously, so that the UI thread will not be occupied, and then when the M method execution ends will return This statement continues down the line.
2. Async
The method that contains the AWAIT keyword must add the async modifier, which can be a Task, task<tresult>, or void return type. A method cannot declare any ref or out parameter, but you can call a method that has such a parameter.
3. Async methods
The method to add the await keyword differs from the general method,
Async methods that do not return a value use the task type as the return type.
Methods with return values use task<tresult> as the return type, TResult is the type of the return value, (void return type can only be used in the event method),
Asynchronous methods typically use Task.run (Action) to create threads.
Example: Async method that requires a return value
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.IO;usingSystem.Security.Cryptography;namespacecrypto{classHash {//Async methods that need to return a value use task as the return value type of the method Public Statictask<string> Getsha1async (stringfileName) { //Creating thread pool threads using Task.run (Action) returnTask.run (() = { stringSha1str =""; if(File.exists (fileName)) {FileStream File=NewFileStream (FileName, FileMode.Open); byte[] SHA1 = SHA1. Create (). ComputeHash (file);//calculating the SHA1 of a filefile. Close (); //use Bitconverter to convert the SHA1 byte array to a 16-binary string, with a "-" split for each byte by default//then the delimiter "-" in the string is removed (replaced with an empty string "")SHA1STR = bitconverter.tostring (SHA1). Replace ("-",""); } returnSha1str; }); } }}//This async method is called in the Click event of a button controlPrivate Async voidButtonsha1jishuan_click (Objectsender, RoutedEventArgs e) {Textboxsha1jishuan.text=""; Groupboxsha1.isenabled=false; stringSHA1 =awaitCrypto.Hash.GetSHA1Async (Textboxfilename.text); Textboxsha1jishuan.text=SHA1; Groupboxsha1.isenabled=true; }
C # Asynchronous programming