Task class
The Task class is an asynchronous operation abstraction provided after .NET 4.0, with the full path to System.Threading.Tasks.Task.
The Task class is used to represent asynchronous operations with no return value, and for asynchronous operations with return values, the subclass Task of the Task class should be used<TResult>. Tasks created by the Task class are added to the thread pool.
The <TResult>main constructors of the Task/Task class are as follows:
Once created, the task can be started using the Start() method:
In actual development, the static method Run() of the Task class or the member method StartNew() of the factory class TaskFactory are more often used to create and start new tasks.
Some common methods in the Task class:
async/await keyword
C# 5.0 introduced the async and await keywords, which gave better support for concurrency at the language level.
async is used to mark async methods: The async keyword is a contextual keyword and will only be treated as a keyword when modifying a method and Lambda, and will be treated as an identifier in other areas. The async keyword can mark static methods, but not entry points (Main() methods).
The return value of the method tagged with async must be <TResult>one of Task, Task, or void. await is used to wait for the result of the asynchronous method:
The await keyword is likewise a contextual keyword and is only considered a keyword in the async tagged method. The await keyword can be used before the async method and Task, and <TResult>Task, to wait for the end of the asynchronous task execution. A simple async method structure is as follows:
It is not that the method is marked with the async keyword, it is an asynchronous method, and the statements that appear directly inside the async method are also executed synchronously,Content executed asynchronously needs to be executed using the Task class。 In fact, an async method that does not contain any await statements will be executed synchronously, at which point the compiler will give a warning.
Simple example, using async/await to output content concurrently on the screen:
Output: (Mono 4.4.0 && ArchLinux x64)
It is not difficult to see from the above program that in the async keyword tagged asynchronous method, the code before using await is executed synchronously, and after await is called, the remaining code runs asynchronously on a separate thread.
|