Article From:https://www.cnblogs.com/zhlziliaoku/p/9218854.html

One, asynchronous function

The concept of asynchronous function. It usually refers to declarations using async modifiers, which can contain await expressions or anonymous functions 1. From a linguistic point of view, these await expressions are interesting.Place: if the value waiting for an expression is not available, the asynchronous function will return immediately; when the value is available, the asynchronous function will return (on the appropriate thread) back to the place to go and continue. Before “in”The process of not executing the next statement before this statement is completed is still unchanged, but no longer blocked.

Two, the basis of asynchronous execution

The asynchronous execution model is full of subsequent operations. That is, an operation will be done after another follow-up operation. The callback function is similar. In net, subsequent operations should be represented by delegate and usually action for receiving the result of asynchronous operation. In fact, the C# compiler will have all the awaitA follow-up operation is built.

In C#5, asynchronous operation processes can be roughly divided into the following processes:

1、Perform some operations.

2、Start asynchronous operation and remember the returned token.

3、Other operations may be performed. (no operation can be performed until the asynchronous operation is completed, and this step is ignored).

4、Wait for the asynchronous operation to complete (through token).

5、Perform other operations.

6、Complete.

 

Two: async is a modifier used when declaring asynchronous methods, and await expressions are responsible for consuming asynchronous operations.

Three. Detailed explanation

 1.Declare the asynchronous method: the method preferably contains the async keyword, and async can appear anywhere before the return type.

2、The return type of the asynchronous method: the caller and the asynchronous method are communicated through the return value, and the return type of the asynchronous method can only be:

void、Task、Task<Result>….

.NET 4 The Task and Task< TResult&gt types in the system represent an operation that may not yet be completed. Task< TResult> inherit from Task. The difference between the two is thatTask< TResult> represents a return value of T type operation, while Task does not need to generate a return value.

The reason why asynchronous methods are designed to return void is compatible with event handlers.

For an asynchronous method, void can only be returned as an event subscriber. In other cases where the return value is required, it is best to declare the method as Task.

3.Waiting mode

 

Leave a Reply

Your email address will not be published. Required fields are marked *