[C #] entering the asynchronous programming world,

Source: Internet
Author: User

[C #] entering the asynchronous programming world,
Going into the world of asynchronous programming-analyzing the order of asynchronous methods (I)

This is the second chapter in the previous article "going into the world of asynchronous programming-getting started with async/await asynchronous programming" (getting started). It mainly discusses asynchronous methods in depth with everyone.

This document describes how to use delegation.

 

Directory
  • Introduction to asynchronous Methods

  • Control Flow

  • Await expression

  • How to cancel asynchronous operations

 

This section describes asynchronous Methods: return the call method immediately before the execution is completed, and complete the task while the call method continues to be executed. Syntax analysis: (1) Keyword: The method header is modified Using async. (2) Requirement: contains N (N> 0) await expressions (if the await expression does not exist, the IDE will issue a warning), indicating the tasks to be executed asynchronously. [Note] thanks to czcz1024 for its amendment and supplement: if not, it will be executed just like a common method. (3) return type: only three types (void, Task, and Task <T>) can be returned ). Task and Task <T> identify that the returned object will complete the work in the future, indicating that the call method and asynchronous method can continue to be executed. (4) parameter: unlimited quantity. However, the out and ref keywords cannot be used. (5) Naming Convention: The method suffix should end with Async. (6) Others: anonymous methods and Lambda expressions can also be used as Asynchronous objects; async is a context keyword; the keyword async must be before the return type. Async keywords:

① Include the async keyword before the return type

② It only identifies that the method contains one or more await expressions, that is, it does not create asynchronous operations.

③ It is the context keyword and can be used as the variable name.

 

Now let's analyze the three types of return values: void, Task, and Task <T>

(1) Task <T>: to call a method, you must obtain a value of the T type from the call. The return type of the asynchronous method must be a Task <T>. The Result attribute of the Task obtains the T-type value from the call method.

1 private static void Main (string [] args) 2 {3 Task <int> t = Calculator. addAsync (1, 2); 4 5 // keep working 6 7 Console. writeLine ($ "result: {t. result} "); 8 9 Console. read (); 10}Program. cs 1 internal class Calculator 2 {3 private static int Add (int n, int m) 4 {5 return n + m; 6} 7 8 public static async Task <int> AddAsync (int n, int m) 9 {10 int val = await Task. run () => Add (n, m); 11 12 return val; 13} 14}View Code

 

(2) Task: if you do not need to obtain the return value from the asynchronous method but want to check the status of the asynchronous method, you can select an object that can return the Task type. However, even if the asynchronous method contains a return statement, nothing is returned.

1 private static void Main (string [] args) 2 {3 Task t = Calculator. addAsync (1, 2); 4 5 // always working 6 7 t. wait (); 8 Console. writeLine ("AddAsync method execution completed"); 9 10 Console. read (); 11}Program. cs 1 internal class Calculator 2 {3 private static int Add (int n, int m) 4 {5 return n + m; 6} 7 8 public static async Task AddAsync (int n, int m) 9 {10 int val = await Task. run () => Add (n, m); 11 Console. writeLine ($ "Result: {val}"); 12} 13}View Code

 

 

Figure 4

Figure 5

(3) void: Call a method to execute an Asynchronous Method without further interaction.

1 private static void Main (string [] args) 2 {3 Calculator. addAsync (1, 2); 4 5 // keep working 6 7 Thread. sleep (1000); // hangs for 1 second and 8 consoles. writeLine ("AddAsync method execution completed"); 9 10 Console. read (); 11}Program. cs 1 internal class Calculator 2 {3 private static int Add (int n, int m) 4 {5 return n + m; 6} 7 8 public static async void AddAsync (int n, int m) 9 {10 int val = await Task. run () => Add (n, m); 11 Console. writeLine ($ "Result: {val}"); 12} 13}Calculator. cs

Figure 6

Figure 7

 

1. The structure of the asynchronous control flow method can be split into three different areas: (1) the part before the expression: All the code from the method header to the first await expression. (2) await expression: code to be asynchronously executed. (3) Part after the expression: the subsequent part of the await expression. Void: exit the control flow. B. Task: set the Task attributes and exit. C. Task <T>: Set the attribute and return value (Result attribute) of the Task and exit. ④ At the same time, the call method will continue to be executed, and the Task object will be obtained from the Asynchronous Method. When a value is required, the execution will be paused until the Result attribute of the Task object is assigned a value. [Difficulty] ① the type of the object returned by await for the first time. The return type is the return type of the synchronous method header, which is irrelevant to the return value of the await expression. ② When it reaches the end of The Asynchronous Method or encounters a return statement, it does not actually return a value, but exits the method. Ii. await expression

The await expression specifies an asynchronous task. By default, the task is executed asynchronously in the current thread.

Each task is an instance of the awaitable class. The awaitable type refers to the type that contains the GetAwaiter () method.

In fact, you do not need to build your own awaitable. Generally, you only need to use the Task class, which is awaitable.

The simplest way is to use Task. Run () in the method to create a Task. [Note] It is executed on different threads.

 

Let's take a look at the example.

1 internal class Program 2 {3 private static void Main (string [] args) 4 {5 var t = Do. getGuidAsync (); 6 t. wait (); 7 8 Console. read (); 9} 10 11 12 private class Do13 {14 // <summary> 15 // get Guid16 /// </summary> 17 // <returns> </returns> 18 private static Guid GetGuid () // compatible with Func <Guid> 19 {20 return Guid. newGuid (); 21} 22 23 // <summary> 24 // obtain Guid25 asynchronously /// </summary> 26 // <returns> </returns> 27 public static async Task getGuidAsync () 28 {29 var myFunc = new Func <Guid> (GetGuid); 30 var t1 = await Task. run (myFunc); 31 32 var t2 = await Task. run (new Func <Guid> (GetGuid); 33 34 var t3 = await Task. run () => GetGuid (); 35 36 var t4 = await Task. run () => Guid. newGuid (); 37 38 Console. writeLine ($ "t1: {t1}"); 39 Console. writeLine ($ "t2: {t2}"); 40 Console. writeLine ($ "t3: {t3}"); 41 Console. writeLine ($ "t4: {t4}"); 42} 43} 44}View Code

Figure 2-1

Figure 2-2

The preceding four tasks. Run () use the Task Run (Func <TReturn> func) form to directly or indirectly call Guid. NewGuid ().

 

Task. Run () supports the methods represented by different Delegate types in 4: Action, Func <TResult>, Func <Task>, and Func <Task <TResult>

1 internal class Program 2 {3 private static void Main (string [] args) 4 {5 var t = Do. getGuidAsync (); 6 t. wait (); 7 8 Console. read (); 9} 10 11 private class Do12 {13 public static async Task GetGuidAsync () 14 {15 await Task. run () => {Console. writeLine (Guid. newGuid () ;}); // Action16 17 Console. writeLine (await Task. run () => Guid. newGuid (); // Func <TResult> 18 19 await Task. run () => Task. run () => {Console. writeLine (Guid. newGuid () ;}); // Func <Task> 20 21 Console. writeLine (await Task. run () => Task. run () => Guid. newGuid (); // Func <Task <TResult> 22} 23} 24}View Code

Figure 2-3 overload of the Task. Run () method

 

Iii. How to cancel asynchronous operations

The CancellationToken and CancellationTokenSource classes allow you to terminate asynchronous methods.

(1) The CancellationToken object contains information about whether the task has been canceled. If the IsCancellationRequested attribute of this object is true, the task needs to stop the operation and return it. The operation on this object is irreversible, you can only modify the IsCancellationRequested attribute of the object once.

(2) CancellationTokenSource can create a CancellationToken object and call the CancellationTokenSource object's Cancel method. This will set the CancellationToken attribute of this object to "IsCancellationRequested" to "true.

[Note] by calling the CancellationTokenSource object's Cancel method, the CancellationToken attribute IsCancellationRequested of the object is set to true instead of canceling the operation.

 

Example

1 internal class Program 2 {3 private static void Main (string [] args) 4 {5 CancellationTokenSource source = new CancellationTokenSource (); 6 CancellationToken token = source. token; 7 8 var t = Do. executeAsync (token); 9 10 // Thread. sleep (3000); // hangs for 3 seconds 11 // source. cancel (); // transmits the cancellation request 12 13 t. wait (token); // Wait until the task execution is completed 14 Console. writeLine ($ "{nameof (token. isCancellationRequested) }:{ token. isCancellationRequested} "); 15 16 Console. read (); 17} 18 19 20} 21 22 internal class Do23 {24 /// <summary> 25 /// asynchronous execution 26 /// </summary> 27 /// <param name = "token"> </param> 28 // <returns> </returns> 29 public static async Task ExecuteAsync (CancellationToken token) 30 {31 if (token. isCancellationRequested) 32 {33 return; 34} 35 36 await Task. run () => CircleOutput (token), token ); 37} 38 39 // <summary> 40 // loop output 41 // </summary> 42 // <param name = "token"> </param> 43 private static void CircleOutput (CancellationToken token) 44 {45 Console. writeLine ($ "{nameof (CircleOutput)} method start to call:"); 46 47 const int num = 5; 48 for (var I = 0; I <num; I ++) 49 {50 if (token. isCancellationRequested) // monitor CancellationToken51 {52 return; 53} 54 55 Console. writeLine ($ "{I + 1}/{num} completed"); 56 Thread. sleep (1000); 57} 58} 59}View Code

Figure 3-1

Figure 3-2 comment out two lines of code

Figure 3-3: execution result of Figure 3-1 and Figure 3-2 (comment out two lines of code)

Is a result chart that does not call the Cancel () method, and does not Cancel the task execution.

 

Call the Cancel () method 3 seconds later to Cancel the task execution:

Figure 3-4: Remove comments

Figure 3-5: Figure 3-1 and figure 3-4 (excluding comments)

 

Summary
  • This section describes the syntax of asynchronous methods, three different return value types (void, Task, and Task <T>), and control processes.
  • Simple and common asynchronous execution method: Task. Run (). [Note] It is executed on different threads.
  • How to cancel asynchronous operations.

 

Portal

Getting Started: getting started with async/await asynchronous programming

 

Link: http://www.cnblogs.com/liqingwen/p/5844095.html

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.