[C #] asynchronous programming,

Source: Internet
Author: User

[C #] asynchronous programming,
Analyze Asynchronous Method order

This is the second chapter in the previous article "getting started with async/await asynchronous programming" (getting started). It is mainly about an in-depth understanding of asynchronous methods. It is recommended that you take a look at this article for a short time.

This document describes how to use delegation.

 

Directory

 

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.

 

The following three types of return values are analyzed: 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. 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) format.

 

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

 

Iii. Cancel asynchronous operations

 

Iv. Exception Handling

 

5. Wait for the task synchronously in the call Method

 

6. Waiting for tasks asynchronously in asynchronous Methods

 

VII. Task. Delay Method

 

Summary

 

Portal

Getting Started: getting started with async/await asynchronous programming

 

 

-- This is the preview version. After finishing the verification, we will put it on the homepage. Sorry for the inconvenience --

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.