The evolution of asynchronous programming models in C # and how to use asynchronous

Source: Internet
Author: User
Tags object object readline

You can use some asynchronous programming in the programming process. In C # 's BCL, many APIs provide asynchronous methods, beginners may be puzzled by the use of various asynchronous methods, this article mainly for you to comb the evolution of asynchronous methods and how to use asynchronous methods.


beginxxx,endxxx Mode

In the. Net Framework 2.0, the most common approach is to use beginxxx, and endxxx such methods. This pattern can be summed up as a method + callback method pattern or called a invokemethod+eventhandler pattern.

The basic process of this model is:

Calling the BeginXxx method
A callback method is passed in the BeginXxx method, which is executed after the execution of the asynchronous method is completed
Calling the EndXxx method, using the EndXxx method blocks the current thread until the asynchronous method returns the result.

Let's look at a FileStream example method, in. Net 2.0, where you need to use Asynchrony:

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

Starting with. Net 4.0, Microsoft introduced tasks. The flexibility of the task itself also makes our asynchronous programming model simpler. The example above can be implemented in. Net 4.5:

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 Xxxasync methods to implement the new asynchronous model in many BCL APIs. The task itself is much more flexible than the callback method, and can be more elegant to implement callbacks, cancellations, and scheduling operations. The way task is used can be seen in the article link I summarized earlier.


Async and await models

To further simplify the asynchronous model, Microsoft introduced the async and await keywords from visual Studio 2012. The model itself is a compiler-based syntactic sugar that generates a StateMachine model after compilation. This can also be simplified in the above example:

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);
}
}
}


about compatibility with asynchronous programming models

If you look at the class library in BCL, you will find that Microsoft has not added a Xxxasync method to each BeginXxx method in the latest version of the class library. In this case, how can we make the new asynchronous model compatible with the old method?

Take Namedpipeserverstream as an example, this class library implements a pipeline function, Microsoft does not update the Xxxasync method for it, you can use TaskFactory to compatible with the new asynchronous model, you can achieve 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);
}

  

So, we can sum up as,. There are two kinds of asynchronous programming models in net:

A model that does not return a call Method + callback method for a Task object
Returns the Xxxasync model of a Task object, and the async,await model

BeginXxx model Microsoft has been gradually considered obsolete, the return task of the asynchronous programming model is now Microsoft's recommended way.



the asynchronous programming model in C #

When reading a file, if the asynchronous model is not used, the entire thread of execution hangs until the file is read, at which point the thread waits until the file is read; If you are reading a file from the network, you can only throw an exception if the network interrupts (while the thread can only be busy, etc.).


Public IAsyncResult BeginReceive (
Ilist<arraysegment<byte>> buffers,
SocketFlags SocketFlags,
AsyncCallback Callback,
Object State)
public int EndReceive (
IAsyncResult asyncresult)


Asynchronous model: There must be a third, the fourth parameter (both can be null), and return a IAsyncResult type, the asynchronous period with hardware-driven listening, without requiring any thread to wait here;
Three technical points of the asynchronous programming Model: The fourth parameter is passed to the callback function


1. Adopt: Manual Adjustment


BeginReceive ();
...
...
EndReceive ();


Take the appropriate time to return the value in EndReceive () that should have been returned in the synchronization model, and return int,accept () to return a socket, but this results in no full ability to perform asynchronously.


Wait until complete: on execution to end. function, the default is static, which can only save a part of the time;


2. Intermittent query


Public interface IAsyncResult {
Object asyncstate {get;}
WaitHandle asyncwaithandle {get;}
Boolean iscompleted {get;}
Boolean completedsynchronously {get;} No need to use
}


Thread Inquiry:


IAsyncResult AR = fs. BeginRead (data, 0, data.) Length, NULL, NULL);
while (!ar. iscompleted) {
Console.WriteLine ("Operation not completed; Still waiting. ");
Thread.Sleep (10);
}//until it is OK to finish
Int32 bytesread = fs. EndRead (AR);

Similar to:


while (!ar. Asyncwaithandle.waitone (false)) {
Console.WriteLine ("Operation not completed; Still waiting. ");
}
Int32 bytesread = fs. EndRead (AR);

3. Callback function


delegate void AsyncCallback (IAsyncResult ar); Delegate of the callback function (the callback function implementation takes the same type of argument and directly passes the function name)
The default is to convert the fourth object argument to the corresponding IAsyncResult parameter of the callback function.
object is a parameter of any type that is passed to a callback function, but a IAsyncResult asyncstate is used to display the conversion
Call end in the callback function. function to complete the asynchronous operation completely. (The callback function may not be defined in a class)
However, some data, such as a buffer at the time of writing a file, may be common to functions that the callback function might want to start calling asynchronously.


Optimization method:


1. Define a class that contains some common data, declare the instance in the main function, and then pass it as the last argument passed to the callback function. (can prevent too much static data)
2. Anonymous delegate: (Solve data sharing problem)


Fs. BeginRead (data, 0, data.) Length,
Delegate (IAsyncResult ar)
{
Int32 bytesread = fs.    EndRead (AR); Note: Call begin with what ..., and be sure to use it to invoke end ...
Fs. Close ();
Console.WriteLine (bitconverter.tostring (data, 0, bytesread));
}, NULL);


3. Let each asynchronous operation take its own pair of processing functions to achieve the highest efficiency.


Delegate's asynchronous Operation model:
Internal sealed class Sumdelegate:multicastdelegate {
 public sumdelegate (Object Object, IntPtr method);
 public UInt64 Invoke (UInt64 N);
 public IAsyncResult BeginInvoke (UInt64 N, AsyncCallback callback, Object object);
 public UInt64 EndInvoke (IAsyncResult result);

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.