C # Multithreading (ii)--synchronous and asynchronous

Source: Internet
Author: User

1. What is asynchronous

If a program calls a method and waits for it to perform all processing before proceeding, we call this method synchronous.

If a program calls a method and returns to the calling method before the method finishes processing, the method is asynchronous.

The benefit of asynchrony is non-blocking, so we can improve the efficiency of the program by making some time-consuming tasks that do not require immediate use of the results to be asynchronous.

2, Async Method 2.1 asynchronous method simple use

The async/await that appear in c#5.0 can easily create and invoke asynchronous methods, async/await features include three parts

1. Calling method: Is the method that invokes the Async method

2.async Method: Async method, called immediately returns to the calling method

3.await expression: Inside an async method, a task that represents an asynchronous execution. An async method can contain multiple await expressions, that is, an async method can have multiple tasks that execute asynchronously.

A simple example:

1       Static voidMain (string[] args)2         {3             //The calling method is main, and the Async method immediately returns4             //The task<int> placeholder means that the task is placed in the plan, and the task eventually returns a result of type int5task<int> value = Doasyncstuff.calcsumasync (5,6);6             //if the Async method is not completed here, block and wait for the7Console.WriteLine ("result:{0}", value. Result);8         }9     }Ten     Static classDoasyncstuff One     { A         //asynchronous summation, method signature modified with Async -         //There are three return values for async methods: -         //Task<t> has a return value, the type of the return value is T the         //Task has no return value but needs to monitor execution state -         //Void is just a call and it doesn't matter. -          Public Static Asynctask<int> Calcsumasync (intAintb) -         { +             //an await expression that represents the task of an asynchronous operation Task.run () creates a task -             intsum =awaitTask.run (() =Getsum (A, b)); +             returnsum; A         } at         Private Static intGetsum (intAintb) -         { -             returnA +b; -         } -}

Async methods Use the Async method modifier, with one or more await expressions in the method, with a return value of only three

①task<t>: If the calling method gets a value of type T from the call, the return value of the Async method is task<t>

②task: If the calling method does not need to get a value from an async method, but needs to check the state of the Async method, the return value can be set to the Task

③void: The return value is set to void if the calling method simply calls the Async method

2.2 Control flow for asynchronous methods

Calling a method invokes an Async method with two control flows, one in the calling method and one in the Async method.

First call the method call Async method to execute the code in the Async method synchronously until the first await expression is encountered (control is given to the Async method)

If the Async method return value is a task or task<t>, the Async method immediately creates an idle task that is returned to the calling method, and the calling method does not wait for the asynchronous task to complete (non-blocking) to execute its own internal code (here control is given to the calling method)

When the task is completed in the first await expression, the Async method continues to execute its internal code (control is given to the Async method)

When you encounter the next await expression, repeat until you encounter a return or execute to the end of the Async method, noting that the Async method does not return a true value at the end, it simply exits.

How to use 2.3 await expression 2.3.1 await

An await expression specifies the task of an asynchronous operation, and we can set task tasks in the most common way:

// 1. Create a new task with Task.run await Task.run (func/Action)//2, executes a method that must be an async method await  Asyncfunc

Below is an example of an asynchronous summation error:

1      class Program2     {3         Static voidMain (string[] args)4         {5task<int> tsum =Asyncstuff.getsumasync ();6task<int> tsub =Asyncstuff.getsubasync ();7             //1, wait until Tsum complete8 Tsum. Wait ();9task[] Tasks ={tsum, tsub};Ten             //2, wait until the tasks are complete One Task.waitall (tasks); A             //3. Wait until one of the tasks is completed - Task.waitany (tasks); -  the             //View the status of tasks - Console.WriteLine (Tsum. Status); - Console.WriteLine (tsub. Status); -             //Record Results + Console.WriteLine (Tsum. Result); - Console.WriteLine (tsub. Result); + Console.readkey (); A         } at     } -     classAsyncstuff -     { -         //Asynchronous Summation -          Public Static Asynctask<int>Getsumasync () -         { in             intsum =0; -             //Task.run (func/action) Create a task to             awaitTask.run (() = +             { -                  for(inti =1; I <1000000; i++) the                 { *Sum + =i; $                 }Panax Notoginseng             }); -             returnsum; the         } +         //Asynchronous seek Error A          Public Static Asynctask<int>Getsubasync () the         { +             intSub =0; -            awaitTask.run (() = $             { $                  for(inti =0; I <1000000; i++) -                 { -Sub-=i; the                 } -             });Wuyi             returnSub; the         } -}

In the example we use the wait, WaitAny, WaitAll implementations to wait for the task to complete synchronously in the calling method, we can also use the Whenany/whenall implementation to asynchronously wait for the task in the Async method, no longer an example.

The Task.delay () method creates a task object that pauses the processing of the asynchronous task and finishes after a certain amount of time, unlike Thread.Sleep, where the Task.delay does not block the thread and the thread can continue to handle other work.

A task.delay example:

1      class Program2     {3         Static voidMain (string[] args)4         {           5Simple SP =NewSimple ();6 sp. Dorun ();7 Console.readkey ();8         }9     }Ten  One     class Simple A     { -Stopwatch SW =NewStopwatch (); -          Public voidDorun () the         { - SW. Start (); -Console.WriteLine ("Caller:before call--{0}", SW. Elapsedmilliseconds); - Showdelyasync (); +Console.WriteLine ("Caller:after call--{0}", SW. Elapsedmilliseconds); -         } +          Public  Async voidShowdelyasync () A         { atConsole.WriteLine ("before delay--{0}", SW. Elapsedmilliseconds); -             awaitTask.delay ( +); -Console.WriteLine ("After delay--{0}", SW. Elapsedmilliseconds); -         } -}

C # Multithreading (ii)--synchronous and asynchronous

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.