. Async and await in the first NET4.5

Source: Internet
Author: User
I'm from. When NET4.0 first came in contact with the. NET environment, so the thing to learn is 4.0 and before. The time is fast ahead, the Eye 5.0 also quickly out of it, but has not been to accept the new technology. Recently, due to learn the Web API, almost finished, but found that 4.5 has been the way, and then the brain. Async and await are one of them:

This is a two-word keyword for asynchronous programming. Our traditional asynchronous programming is usually thread, ThreadPool, BeginXXX, EndXxx, and so on. By separating calls and callbacks, the logic of the code is leaping, which leads to a problem that is not very clear, and in. NET 4.5, the new async, await keyword can help us write asynchronous methods like write synchronization methods (to keep the code neat and clear).
Let's take a look at a traditional sync Method Example:
  

static void Main (string[] args)
{
    //Sync Way
    Console.WriteLine ("Sync mode Test begins.") ");
    Syncmethod (0);
    Console.WriteLine ("Sync ended.") ");
    Console.readkey ();
}

Synchronous operation
private static void Syncmethod (int input)
{
    Console.WriteLine ("Enter a synchronization operation.") ");
    var result = Syancwork (input);
    Console.WriteLine ("Final results {0}", result);
    Console.WriteLine ("Exits the sync operation.) ");
}

Simulate time-consuming operation (sync method)
private static int syancwork (int val)
{for
    (int i = 0; i < 5; ++i)
    {
        Console. WriteLine ("Time-consuming operation {0}", i);
        Thread.Sleep (m);
        val++;
    }
    return val;
}

The

can see the execution results from the right figure, which is a very typical synchronous execution method. The
Async keyword can be used in the declarations section of a method, lambda expression to indicate that this method may contain await keywords, and only async can use the await keyword within it. An asynchronous method can have a return type of Task, task<>, or void; the await keyword is in a method or lambda expression that returns a value that is a "can Wait" type (awaitable), "awaitable" can be any type (common with tasks, task<>), it must expose a getawaiter () method and return a valid "Awaiter". For more detailed information, refer to the FAQ on async and await, which describes these concepts and considerations.
When a async method is included and contains the await keyword internally, it becomes an asynchronous method at compile time, and if there is no await keyword, it will only be executed as a synchronous method. If you are interested in its internal implementation, you can refer to the article "Asynchronous performance: Understanding the cost of Async and Await", and I believe it is helpful to understand this mechanism in depth.
Now we are trying to use the new asynchronous keyword async, await to make an asynchronous call:

static void Main (string[) args) {//Asynchronous mode Console.WriteLine ("\ n asynchronous method test started.
     ");
     Asyncmethod (0); Console.WriteLine ("Asynchronous Mode end.")
     "); 
 Console.readkey (); }//Asynchronous operation private static async void Asyncmethod (int input) {Console.WriteLine ("Enter an asynchronous operation.")
     ");
     var result = await asyncwork (input);
     Console.WriteLine ("Final results {0}", result); Console.WriteLine ("Quits the asynchronous operation.)
 "); 
         }//Simulate time-consuming operation (asynchronous method) private static async task<int> asyncwork (int val) {for (int i = 0; i < 5; ++i) {
         Console.WriteLine ("Time-consuming operation {0}", i);
         Await Task.delay (100);
     val++;
 return Val; }

Look at the results first, we found that the time-consuming operation is already asynchronous. The overall process is probably the first by the main function asynchronous call Asyncmethod, do not wait for Asyncmethod to complete, continue to execute. The Asyncmethod method, after being invoked, starts at the time it is allocated, executes the function body content, and continues to invoke asyncwork asynchronously due to the await Asyncwork statement, but because of the await keyword, it waits for asyncwork to complete and continue to carry it down. Ayncwork, then, is also the same, after being invoked, to start up when allocated to the time period, to perform time-consuming operations.
You can see that the syntax difference between synchronization and asynchronous programming is further reduced after new keywords are used. With the introduction of. NET 4.5, many new class libraries and existing class libraries support this new type of asynchronous syntax (such as HttpClient, Httpserver, MemoryStream ...). ), which provide an asynchronous way of working with async declarations and return types of task, task<>, in a separate way like Readasync, WriteAsync, and SendAsync.
Add:
Just now a friend mentioned await Task.delay (100), which is to make Asyncwork an asynchronous method, and if the operation you're going to do doesn't support await modification, it's really simple, Use Task.Factory.StartNew () For example:

Asynchronous operation
private static async void Asyncmethod (int input)
{
    Console.WriteLine Enter an asynchronous operation. ");
    var result = await Task.Factory.StartNew ((Func<object, int>) SYNCWORK2, input);
    Console.WriteLine ("Final results {0}", result);
    Console.WriteLine ("Quits the asynchronous operation.) ");
}

Simulate time-consuming operation (synchronous method)
private static int SyncWork2 (object input)
{
    int val = (int) input;
    for (int i = 0; i < 5; ++i)
    {
        Console.WriteLine ("Time-consuming operation {0}", i);
        Thread.Sleep (m);
        val++;
    }
    return val;
}

In this way, our SYNCWORK2 is actually executed asynchronously, and the result is consistent with the previous asynchronous method, except that the input parameter can only be type object and requires type conversion. In addition to startnew, we can create a new task and call run to accomplish the same effect.
At present, this asynchronous work will still cause my use of discomfort, but if in the future version, continue to promote the use, I believe that soon will be proficient, and speed up the writing code, write a logically clear code.

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.