. net4.5 use Async and await asynchronous programming instances

Source: Internet
Author: User
Tags readline
New features of asynchronous programming async and await are added to the. NET4.5, making asynchronous programming simpler. The feature allows this complex work to be done by the compiler. Before the traditional way to achieve asynchronous programming is more complex, so for the program ape to deal with more difficult, debugging is not so convenient, follow-up maintenance work is also more painful.


The async and await keywords are at the heart of C # asynchronous programming. By using these two keywords, you can use the. NET Framework or Windows runtime resources to create an asynchronous method as easy as creating a synchronization method.
Next, create a VS2013 based on the. NET4.5 the console application to try it.

Just post the simple code first, as shown below

<summary>
        ///sync method Print Hello World
        ///</summary> public
        static void Printhelloworld ()
        {
            Console.WriteLine ("Start of synchronous method call");
            Console.WriteLine ("Sync Method: Hello World");
            Thread.Sleep (1000);
            Console.WriteLine ("Exit Sync Method");
        }
        <summary>
        ///Asynchronous method print Hello World
        ///</summary> public
        async static void Asyncprinthelloworld ()
        {
            Console.WriteLine ("Start of asynchronous method call");
            Console.WriteLine ("Asynchronous Method: Hello World");
            Await Task.delay (1000);
            Console.WriteLine ("Exit Asynchronous Method");
        }

It is also explained in the note above, the first is the synchronization method, and the second is the asynchronous method. The synchronous method can be performed by the Thread.Sleep (1000), suspend method 1000ms, the same asynchronous method can be handled by await Task.delay (1000), and the Async keyword is added to the declaration of the asynchronous method.
The following is a simple call

static void Main (string[] args)
        {
            Console.WriteLine ("= = = = = = = = = = = = = = = = =====");
            Printhelloworld ();
            Console.WriteLine ("Synchronous Method call End");
            Console.WriteLine ("= = = Asynchronous method call =====");
            Asyncprinthelloworld ();
            Console.WriteLine ("End of asynchronous method call");
            Console.ReadLine ();
        }

The results of F5 execution are as follows



It is clear from the results of the execution that the synchronous method of the invocation is executed sequentially, but in asynchronous methods, the following method outside of its method continues to execute when the current method is paused through Task.delay (1000), which is to print the statement "End of the asynchronous method call".


You can see that there is little difference between synchronization and asynchronous syntax after using a keyword. With. With the introduction of NET4.5, many class libraries and existing class libraries will support this new type of asynchronous syntax, such as the httpclient I am learning and so on.
The above demo is only demonstrated with a simple void method, certainly with the amount of the return value.

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading;
Using System.Threading.Tasks;
Namespace Async
{
    class program
    {
        static void Main (string[] args)
        {
            var ret = Asyncadd ("Exhausted, Really can't think of a good example to call ");
            Console.WriteLine (ret. result);
            Console.ReadLine ();
        }
           
        Asynchronously prints incoming string public
        async static task<string> Asyncadd (String str)
        {
            string result = await Pringstring (str);
            return result;
        }
        Public async static Task<string> pringstring (String str)
        {return
            ' Hello world ' + str;
        }
    }
}

By running it is the same as synchronizing, except to see how to define the return value of the asynchronous method, which is defined according to task<t>.


If the specified task<tresult> is the return result, the method must contain a statement that returns the specified TResult result.


A async method usually contains one or more corresponding await operators, but it does not cause a compilation error if there is no await expression. However, if you call a async method, but do not use the AWAIT keyword to mark a hanging starting point, the program ignores the ASYNC keyword and executes it in a synchronized manner


Summarize
1. A async modifier must be included in the declaration of an asynchronous method.
2. The method name of the asynchronous method can end with "Async".
3.task<tresult> when your method has a return value, then TResult is the type of the return value
4. A method usually contains at least one await expression.


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.