C # async / await structure

Forced to explain:

Synchronization method: a program call a method, after the completion of its execution to wait until the next step. This is the default form.

Asynchronous Methods: A program calls a method, processing is complete before the method returns. By async / await us on this type of approach can be achieved.

 

Start the topic:

async / await structure may be divided into three parts:

    (1) call the method: This method is called asynchronous method, and then continue when the asynchronous method execution of its mandate;

    (2) the asynchronous method: This method is asynchronous implementation, and then return immediately to the calling method;

    (3) await expression: for internal asynchronous method, pointed out that the task should execute asynchronously. The method may comprise a plurality of asynchronous await expressions (expressions do not exist, then await the IDE warn).

      Asynchronous Methods: The method returns the call immediately before the execution is complete, complete the task in the process of calling the method continues execution.

    Parsing:

    (1) Keywords: head using async methods modified.

    (2) Requirements: comprising N (N> 0) th await expression (await expression does not exist will warn IDE), it indicates the need of asynchronous tasks.

    (3) Return Type: only 3 types of return (void, Task and the Task <T>). Task and Task <T> object identifier will be returned to complete the work in the future, represents the asynchronous method call methods and can proceed.

    (4) Parameter: Any number, but can not use keywords out and ref.

    (5) naming convention: Async method extension should end.

    (6) Other: Anonymous Lambda expressions and methods may also be used as an asynchronous objects; async is a context keyword; async keyword must precede the return type.

    About async keyword:

  ① containing the async keyword before the return type

  ② it is only the method comprises identifying one or more await expression, i.e., does not create its own asynchronous operation.

  ③ It is a context keyword can be used as a variable name. async / await structure

 

For now a simple analysis of the return value of these three types: void, Task and Task <T>

  (1) Task <T>: calling method calls to obtain the value from a T type asynchronous method return type must be Task <T>. Call the method to get the value of that property from the Task Result of type T.

internal class Calculato
        {
            private static int Add(int n, int m)
            {
                return n + m;
            }
            public static async Task<int> AddAsync(int n, int m)
            {
                int val = await Task.Run(() => Add(n, m));
                return val;
            }
        }

    (2) Task: calling method need not take the value returned from the asynchronous method, but want to check the status of the asynchronous method, the object may be selected Task may return type. However, even if the asynchronous method contains the return statement, it will not return anything.

internal class Calculato
        {
            private static int Add(int n, int m)
            {
                return n + m;
            }
            public static async Task<int> AddAsync(int n, int m)
            {
                int val = await Task.Run(() => Add(n, m));
                return val;
            }
        }

 

    Control Flow

    Structure asynchronous method can be split into three distinct areas:

    Section prior to the expression (1): all code from among a first method of the first to await expression.

    (2) await expression: the code will be executed asynchronously.

    (3) after the portion of the expression: await a subsequent part of the expression.

   This method performs an asynchronous process: start from where you await the expression of a synchronous execution to await, identification section performs the first end, generally at this time have not await the completion of the work. When await the completion of the task, which will continue to perform the subsequent synchronization portion. In the subsequent part of the implementation, if the await still exists, the above process is repeated.

  When you reach the await expression, threads from asynchronous method returns to the calling method. If the return type of the asynchronous method for Task or Task <T>, will create a Task object, identifies the need for asynchronous tasks, and then to call methods Task returns.

 

    Flow control asynchronous method:

  ① executed asynchronously await expression of the idle task.

  ②await expression execution is complete, proceed to the subsequent section. As we encounter await expression, is processed in the same situation.

  ③ When it reaches the end or return statement encountered, based on the return type can be divided into three cases:

    a.void: exit control flow.

    b.Task: Set Task Properties and exit.

    c.Task <T>: Task set properties and return values ​​(Result property) and exit.

  ④ At the same time, the calling method will continue to get the Task object from an asynchronous method. When necessary value, the Result property will be suspended until the Task object is assigned will continue.

  【difficulty】

  ① first encountered types await the return of the object. The return type is the head of the synchronization method return type, with await the return value of the expression does not matter.

  ② reached the end of the asynchronous method or encounters a return statement, it does not really return a value, but withdrew from the process.

expression specifies the tasks that await an asynchronous execution. By default, the asynchronous task execution in the current thread.

  Each task is an instance of a class awaitable. awaitable type refers to the type comprising GetAwaiter () method.

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

  The easiest way is to use the method Task.Run () to create a Task. [Note] it is to perform method on a different thread.

Describes asynchronous method syntax, three types of return value (void, Task and the Task <T>), and the like different from the control flow.

Simple common asynchronous execution mode: Task.Run (). [Note] it is to perform method on a different thread

First, exception handling

  await expressions can also use the try ... catch ... finally structure.

Second, the synchronization method call waiting tasks

  Methods may call at some point in time need to wait for a special Task object is completed, before the implementation of the code behind. In this case, examples of methods may be employed Wait.

internal class Program

    {

        private static void Main(string[] args)

        {

            var t = CountCharactersAsync("http://www.cnblogs.com/liqingwen/");

            t.Wait();  //等待任务结束

            Console.WriteLine($"Result is {t.Result}");

            Console.Read();

        }

        /// <summary>

        /// 统计字符数量

        /// </summary>

        /// <param name="address"></param>

        /// <returns></returns>

        private static async Task<int> CountCharactersAsync(string address)

        {

            var result = await Task.Run(() => new WebClient().DownloadStringTaskAsync(address));

            return result.Length;

        }

    }

 

Published 105 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_38890412/article/details/104041154