Async await Task, asyncawaittask
I. Use Task
Reference namespace
Using System. Threading. Tasks;
1. Factory method
Task. Factory. StartNew () => {Console. WriteLine ("Hello Task library! ");});
2. instance mode
Task task = new Task () => PrintMessage (); task. Start ();
3.. NET4.5
Task. Run () => PrintMessage ());
// Wrap the specified result as a completed Task
Task. FromResult <
Int
> (GetSum (4, 5 ));
Ii. async and await
Async and await
(1) In the method body identified by async, if there is no await keyword, this method is no different from calling a common method.
(2) In the method body identified by async, before the await keyword appears, it is still called by the main thread in sequence until the await keyword appears.
(3) The await keyword can be understood as waiting for the method to complete execution. In addition to marking the method with the async keyword, it can also mark the Task object, indicating waiting for the thread to complete execution. Therefore, the await keyword is not for the async method, but for the Task that the async method returns to us.
(4) The return type of the asyc method must be void, Task, or Task <T>. That is to say, async is either void or associated with Task.