About the changes in the asynchronous programming model in c,

Source: Internet
Author: User

About the changes in the asynchronous programming model in c,

Some asynchronous programming scenarios will be used in the programming process. In c #'s BCL, many APIs provide asynchronous methods. Beginners may be confused about the use of different asynchronous methods, this article describes the changes of asynchronous methods and how to use them.

BeginXXX, EndXXX Mode

In. Net Framework 2.0, the most common method is BeginXXX, which can be used together with EndXXX. This mode can be summarized as the method + callback method mode or the InvokeMethod + EventHandler mode.

The basic process of this model is:

Let's look at a FileStream example method. In. Net 2.0, you need to use Asynchronization like this:

using System;using System.IO;using System.Text;public class AsyncTest{    public static void Main(string[] args)    {        using (FileStream file = new FileStream("Test.txt", FileMode.OpenOrCreate))        {            var bytes = Encoding.UTF8.GetBytes("Test for .net framework 2.0");            IAsyncResult asyncResult = file.BeginWrite(bytes, 0, bytes.Length, callback, null);            file.EndWrite(asyncResult);        }        Console.ReadLine();    }    private static void callback(IAsyncResult ar)    {        Console.WriteLine("Finish Write");    }}
XXXAsync Mode

Microsoft introduced Task from. Net 4.0. The flexibility of tasks makes our asynchronous programming model more concise. The above example can be implemented in. Net 4.5 as follows:

using System;using System.IO;using System.Text;using System.Threading.Tasks;public class AsyncTest{    public static void Main(string[] args)    {        using (FileStream file = new FileStream("Test.txt", FileMode.OpenOrCreate))        {            var bytes = Encoding.UTF8.GetBytes("Test for .net framework 4.5");            var task = file.WriteAsync(bytes, 0, bytes.Length);            task.Wait();        }        Console.ReadLine();    }}

Microsoft has added the XXXAsync method to many BCL APIs to implement the new asynchronous model. The Task itself is much more flexible than the callback method, and can implement callback, cancellation, scheduling, and other operations more elegantly. For how to use tasks, see link in my previous summary.

Async and await Models

To further simplify the asynchronous model, Microsoft introduced async and await keywords from Visual Studio 2012. This model is a syntactic Sugar Based on the compiler. After compilation, A statemachine model is generated. The preceding example can also be simplified:

using System;using System.IO;using System.Text;using System.Threading.Tasks;public class AsyncTest{    public static void Main(string[] args)    {        TestFunc();    }    private static async void TestFunc()    {        using (FileStream file = new FileStream("Test.txt", FileMode.OpenOrCreate))        {            var bytes = Encoding.UTF8.GetBytes("Test for .net framework 4.5");            await file.WriteAsync(bytes, 0, bytes.Length);        }    }}
Compatibility of asynchronous programming models

If you pay attention to the class library in the BCL, you will find that Microsoft has not added the XXXAsync method to every BeginXXX method in the latest class library. In this case, how can we make the new asynchronous model compatible with the old method?

Taking NamedPipeServerStream as an example, this class library implements the function of a pipeline. Microsoft has not updated the XXXAsync Method for it. You can use TaskFactory to be compatible with the new asynchronous model. You can implement it like this:

    private static void OldAsyncModel()    {        NamedPipeServerStream pipe = new NamedPipeServerStream("customPipe", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough);        IAsyncResult async = pipe.BeginWaitForConnection(callback, null);        pipe.EndWaitForConnection(async);    }    private static async void NewAsyncModel()    {        NamedPipeServerStream pipe = new NamedPipeServerStream("customPipe", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough);        await Task.Factory.FromAsync(pipe.BeginWaitForConnection, pipe.EndWaitForConnection, null);    }

  

Therefore, we can conclude that. Net has two asynchronous programming models:

The BeginXXX model has been gradually abandoned by Microsoft. the asynchronous programming model for returning tasks is currently recommended by Microsoft.


Author: Tall Buildings
Source: http://www.cnblogs.com/myprogram/
The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.

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.