C # Asynchronous programming

Source: Internet
Author: User

What is asynchronous programming

What is asynchronous programming? To give a simple example:

usingSystem.Net.Http;usingSystem.Threading.Tasks;using StaticSystem.Console;namespacecore{classAsync {Static voidMain () {Start ();        End (); }        Static voidWait () =>writeline ("Waiting ..."); Static voidEnd () =>writeline ("End ..."); Static intStart () {WriteLine ("start ..."); HttpClient Client=NewHttpClient ();            Waiting (); varresult = client. Getstringasync ("https://www.visualstudio.com/"); stringstr =result.            Result; returnStr.        Length; }    }}

In the above code, the code in the main method is executed in the top-down order. When the network is in poor condition, the Start() method is time-consuming (note that the Async method is called in the method here, Start GetStringAsync But the method is executed synchronously here, as explained below), and the Start() entire program is blocked until the method finishes executing. Asynchronous programming can be a good solution to this problem, a simple word to summarize asynchronous programming is that the program does not need to follow the code order from top to bottom execution .

async/await

c#5.0 new Async and await keywords, using these two keywords can greatly simplify asynchronous programming

If you are using the keyword async when defining a method, then this method is an asynchronous method, such as:

 Public Async Task Asy () {}

Use the async keyword To specify a method, lambda expression, or anonymous method as asynchronous. One thing to note here is that if the await keyword is not used in an async method, the Async method will be executed synchronously.

Several requirements for defining asynchronous methods

Defining an Async method should meet the following points:

    • Use the Async keyword to modify a method
    • Use the await keyword in an async method (without the compiler giving a warning but not an error), otherwise the Async method executes synchronously
    • Try not to use void as the return type, and if you want the Async method to return a void type, use the task
    • Async method name ends with async
    • Variables decorated with the ref or out keyword cannot be declared in an async method

The following defines an async method StartAsync() :

Static Async task<int> startasync () {    new  HttpClient ();     var await the client. Getstringasync ("https://www.visualstudio.com/");     return Str. Length;}
The return type of an async method
    • Task<t>
      If the await keyword is used when calling an anonymous method, and the return type of the anonymous method is Task<t>, then the return type we get is T. If the await keyword is not used, the return type is a task. When await is not used, result is a task type when the Getstringasync method is called.

  

Since we can see that the await keyword was not used when calling the Getstringasync method, result is a task type, and we can get the detailed type information for result by using the GetType () method:

The full name of the type from which you can see the result is System.Threading.Tasks.Task


From what we can see when using the await keyword, result is of type string, and the return type of the anonymous method Getstringasync is task<string>

    • Task
      If the await keyword is used when an anonymous method is called, and the return type of the anonymous method is a task, then the return type we get is void. If the await keyword is used, the resulting return type is a task.

    • void
      Void is not recommended as the return value of an async method.
      Because the task or task<tresult> tasks are used as return values, their properties carry information about their state and history, such as whether the task is complete, whether the Async method causes an exception or is canceled, and what the final result is. These properties are accessible by the await operator.

Asynchronous method Execution Flow
Asynchronous program execution Process


is an official Microsoft-provided illustration of the asynchronous program execution process, with explanatory notes:

The numbers in the diagram correspond to the following steps.

  1. An event handler calls and awaits the Accessthewebasync async method.
  2. Accessthewebasync creates an HttpClient instance and calls the Getstringasyncasynchronous method to download the contents of a website as a string.
  3. Something happens in Getstringasync the suspends its progress. Perhaps it must wait for a website to download or some other blocking activity. To avoid blocking resources, Getstringasync yields control to its caller, Accessthewebasync.
    getstringasync Returns a task<tresult> where TResult is a string, and Accessthewebasync assigns th e task to thegetstringtask variable. The task represents the ongoing process for the call to Getstringasync, with a commitment to produce an actual St Ring value when the work was complete.
  4. Because getstringtask hasn ' t been awaited yet, Accessthewebasync can continue with other work this doesn ' t depend on the F Inal result from getstringasync. That's represented by a call to the synchronous method Doindependentwork.
  5. Doindependentwork is a synchronous method, does its work, and returns to its caller.
  6. Accessthewebasync have run out of the work of the It can do without a result from getstringtask. Accessthewebasync next wants to calculate and return the length of the downloaded string, but the method can ' t calculate t Hat value until the method has the string.
    Therefore, Accessthewebasync uses an await operator to suspend their progress and to yield control to the method that called Accessthewebasync. Accessthewebasync returns atask<int>to the caller. The task represents a promise to produce an integer result that's the length of the downloaded string.

    Note
    If Getstringasync (and therefore getstringtask) is complete before accessthewebasync awaits it, control remains I Naccessthewebasync. The expense of suspending and then returning to Accessthewebasync would is wasted if the called Asynchronous process (GetS Tringtask) has already completed and Accessthewebsync doesn ' t having to wait for the final result.
    Inside the caller (the event handler in this example), the processing pattern continues. The caller might do and the doesn ' t depend on the result from Accessthewebasync before awaiting that result, or th E caller might await immediately. The event handler is waiting for Accessthewebasync, and Accessthewebasync are waiting for getstringasync.

  7. Getstringasync  completes and produces a string result. The string result isn ' t returned by the call to  Getstringasync  in The "the" and "you might expect" . (Remember that the method already returned a task in step Instead, the string result was stored in the task that represents The completion of the method, Getstringtask. The await operator retrieves the result from Getstringtask. The assignment statement assigns the retrieved result to urlcontents.
  8. When Accessthewebasync had the string result, the method can calculate the length of the string. Then the work Ofaccessthewebasync are also complete, and the waiting event handler can resume. The full example at the end of the topic, you can confirm that the event handler retrieves and prints the value of the Length result.
    If You is new to asynchronous programming, take a minute to consider the difference between synchronous and asynchronous Behavior. A synchronous method returns when it is complete (step 5), but an async method returns a task value Suspended (steps 3 and 6). When the Async method eventually completes it work, the task was marked as completed and the result, if any, was stored in The task.

Although the explanation is English, but not too difficult words, can understand its meaning. Through the above instructions, we can know:
Before encountering the awiat keyword, the program executes from top to bottom in code order, in a synchronous manner.
After encountering the await keyword, the system does the following:

    1. Async method will be suspended
    2. Return control to the caller
    3. The result of an await expression is evaluated using a thread in the thread pool instead of the additional creation of a new thread, so the await does not cause the program to block
    4. After you have finished evaluating the await expression, continue executing the code if there is code behind the await expression

Use a piece of code to verify:

Static voidMain () {Task<int> task =Startasync (); Thread.Sleep ( the); End ();}Static Asynctask<int>Startasync () {WriteLine ("start ..."); HttpClient Client=NewHttpClient (); varresult = client. Getstringasync ("https://www.visualstudio.com/"); stringstr =awaitresult; returnStr. Length;}

Execute code


As you can see from the call stack on the left, async methods execute top-down synchronously before encountering the await keyword StartAsync . Note that the Async method GetStringAsync method Here is suspended, does not cause the program to block, control back to the caller StartAsync , carefully read the 3rd step in the English explanation.
Then enter the System.Threading.Thread.Current view current worker thread information in debug console and System.Threading.Thread.CurrentThread.IsThreadPoolThread see if the current thread is in the threads pool.


From what we see, the current thread ID is 1, not in thread pool. To continue executing the program:


After encountering the await keyword, the async method StartAsync is suspended and control is returned to the caller's main method.



From the value of the status property of the result variable that we can see StartAsync in the Async method is WaitingForActivation , the result property value is Not yet computed .

The code continues execution, suspends the main method for 5 seconds, and the system uses threads in the thread pool to calculate the value of the await expression:


From what we can see, the program has successfully computed the value of the await expression, and the value of the status property of the variable result becomes RanToCompletion . After the calculation of the await expression is completed, the program continues to execute the following code ( return str.Length ).

Then look at the worker thread information at this point:

We see that the current thread ID is 5 and exists in the thread pool.

From here we can learn that async is implemented by multithreading .

Task

The task class has two methods for executing async methods:, and Task.Run() Task.Run<T> using threads Task.Run Task.Run<T> in the thread pool to execute code. The difference between it and using the await keyword is that Task.run uses threads in the thread pool directly, and the Async method using await is to use multithreading after encountering the await keyword.

Thread

Threads are the basis of the previously mentioned asynchronous (async/await) and Task (Task). Another concept that is closely related to threads is the process, which is not a lot to repeat.

ThreadPool

Threads are also objects, and frequent creation and destruction of thread comparisons affect performance. NET provides a thread pool that allows us to reuse thread objects to avoid frequent creation and destruction of threads.

Conclusion

Create a thread of their own trouble but better control of the operation of the program, using the ASYNC/AWAIT keyword to encode is more concise, but the process of controlling the intensity will be reduced.

Reference article:

Asynchronous programming with Async and await (C #)
Async
Await
Go into the world of asynchronous programming-start contacting async/await
C # Several ways to perform asynchronous operations comparison and summary
Thread Task Parallel PLINQ async await multithreaded tasks and asynchronous programming
Stepping into the world of asynchronous programming-performing asynchronous operations in the GUI

Copyright notice

This article is the author original, the copyright belongs to the author Snow Feihong all. Reproduced must retain the integrity of the article, and in the page marked the location of the original link.

If you have questions, please email and contact the author.

C # Asynchronous programming

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.