Have to say asynchronous programming

Source: Internet
Author: User
Tags apm

1. What is asynchronous programming?

Asynchronous programming is the process of putting time-consuming operations into a separate thread (the thread needs to reflect the execution progress to the interface). Because the time-consuming operation is executed in another thread, it does not block the main thread. After the main thread has opened these separate threads, you can continue to perform other operations (such as form drawing, etc.).

Asynchronous programming can improve the user experience and prevent users from seeing the program "Die" during time-consuming operations.

2. Asynchronous programming Model (APM)

APM is the abbreviation for Asynchronous Programming mode, the meaning of the asynchronous programming model, which allows the program to perform more operations with fewer threads. In the. NET framework, to distinguish whether a class implements an asynchronous programming model, the main thing is to see if the class implements the BeginXxx method and EndXxx method that returns the type IAsyncResult interface.

Because the delegate type defines the BeginInvoke and EndInvoke methods, the delegate type implements the asynchronous programming model.

2.1 BeginXxx Method--Start asynchronous operation

When we need to get the contents of a file, we usually read it using FileStream's synchronous method, which is defined as:

public override int Read (byte[] array,int offset,int count)

When you use the above method to read the contents of a large file, the UI thread is blocked, causing the form to become unresponsive if the user cannot perform any action on the form (including closing the application) until the contents of the file have been read finished.

In order to solve this problem, Microsoft introduced the asynchronous programming model in. NET 1.0, and provided the method implementation of asynchronous Pattern for the FileStream class, namely the BeginRead method. The method asynchronously executes the read operation and returns the object that implements the IAsyncResult interface, which stores information about the asynchronous operation.

The definition of the BeginRead method is given below, and we can find out how it differs from the synchronous method read:

public override IAsyncResult BeginRead (byte[] array,int offset,int numbytes,asynccallback usercallback,object StateObject)

From the definition of the asynchronous method above, we can see that the first 3 parameters of the asynchronous method are consistent with the synchronous method read, and the latter two parameters Usercallback and StateObject are not available in the synchronous method. Usercallback represents a method that requires a callback after the asynchronous operation completes, which must match the AsyncCallback delegate type; StateObject represents the object passed to the callback method, in the callback method, The object can be read by querying the AsyncState property of the IAsyncResult interface. The Async method does not clog the UI thread because it returns control to the calling thread immediately after it is called (if the method is called by the UI thread), then the control is returned to the UI thread, and then another thread executes the file read operation.

2.2 EndXxx Method--end asynchronous operation

Each time the BeginXxx method is called, the application needs to call the EndXxx method to get the result returned by the operation. The BeginXxx method returns the object that implements the IAsyncResult interface, which is not the result returned by the corresponding synchronization method. You also need to call the EndXxx method to end the asynchronous operation and pass the object returned by BeginXxx to the method. The EndXxx method returns the same type as the synchronization method, such as the FileStream EndRead method returns a Int32 type that represents the number of bytes actually read from the file stream.

The EndXxx method is called in many ways, but one is most commonly used, that is, using the AsyncCallback delegate to specify the method to invoke when the operation is complete, calling the EndXxx method in the callback method to get the result returned by the asynchronous operation.

1 Static voidMain ()2 {3SynchronizationContext sc=synchronizationcontext.current;4Asyncmethodcaller methodcaller=NewAsyncmethodcaller (downloadfileasync);5Method. BeginInvoke (TxtUrl.Text.Trim (), GetResult,NULL);6 }7 Private Static voidGetrsult (IAsyncResult result)8 {9Asyncmethodcaller caller=( Asyncmethodcaller) ((AsyncResult) result). AsyncDelegate;Ten     stringreturnstring=Call . EndInvoke (result); One}

3. Asynchronous programming Model (EAP)

Although the preceding asynchronous programming solves the problem that the interface cannot respond when the time-consuming operation is performed, there are obvious problems with APM, such as the failure to support cancellation of asynchronous operations and the inability to provide download progress reports. For desktop applications, however, the ability to report and cancel operations is essential, so Microsoft introduced a new asynchronous programming model-the event-based Asynchronous model, EAP (event-based asynchronous Pattern)-in. NET 2.0.

The class that implements the EAP has one or more methods that are suffixed with async, and the corresponding completed events, and these classes support the cancellation and progress reporting of asynchronous methods. In the. NET class library, only a subset of the classes implemented EAP, a total of 17. Of the 17 classes, the most used in the development process is the BackgroundWorker class.

The frequently used properties are:

Cancellationpending: Used to indicate whether the application has requested cancellation of background operations;

IsBusy: Indicates whether the asynchronous operation is running;

Workreportprogress: Just backgrounworker can report progress;

Workersupportscancellation: Indicates whether the Backgroundwoker supports asynchronous cancel operation;

The frequently used methods are:

CancelAsync: request cancel asynchronous operation;

ReportProgress: Used to trigger progresschanged events;

Runworkasync: Executes asynchronous operation after invocation;

The 3 frequently used events are:

DoWork: Event triggered when invoking Runwokerasync;

ProgressChanged: The event that is triggered when the reportprogress is called, and the program updates the progress report in the event;

RunWorkerCompleted: Triggered when an asynchronous operation is completed, canceled, or an exception is thrown.

This method is rarely used, so this is not covered in detail here.

4. What is tap?

described earlier. NET provides two asynchronous programming patterns, respectively, for APM in. NET 1.0 and EAP in. NET 2.0. While both asynchronous programming patterns can implement asynchronous programming in most cases, they are annotated in the MSDN documentation for deprecated implementations, because in. NET 4.0, Microsoft offers a simpler way to implement asynchronous programming--tap, a task-based Asynchronous Pattern.

This pattern uses the Task<t> class in the System.Threading.Tasks namespace primarily to implement asynchronous programming, so you first introduce the System.Threading.Tasks namespace before using tap.

The task-based Asynchronous Pattern (tap,task-based Asynchronous Pattern) uses only one method to represent the beginning and completion of an asynchronous operation, whereas APM requires BeginXxx and endxxx two methods to represent the beginning and the end respectively. EAP requires a method with an async suffix and one or more events. In the task-based Asynchronous Pattern, only one method with the Taskasync suffix is required, and by passing the CancellationToken parameter to the method, we can complete the asynchronous programming well. It is also possible to implement progress reporting through the Iprogress<t> interface. In general, using tap will reduce our workload and make the code more concise.

1 Task task=New Task (() ={...}); 2 task. Start ();

5. Async and await in async programming so easy--c# 5.0

Although both. NET 1.0 and. NET 2.0 and. NET 4.0 are well supported for asynchronous programming, Microsoft has gradually made it easier to use asynchronous programming, but Microsoft feels that the current work is not enough and it wants to make the development of asynchronous programming more streamlined, so in. NET 4.5, Microsoft has also proposed async and await two keywords to support asynchronous programming.

This is also the simplest way to implement asynchronous programming in the. NET framework now, because using this two keyword for asynchronous programming is exactly the same as when you are implementing synchronous programming.

The async and await keywords do not let the calling method run in a new thread, but instead divide the method into multiple fragments (the bounds of the fragment appear at the location where the await keyword is used inside the method) and some of the fragments can be run asynchronously. The code snippet at the await keyword is run on the thread pool threads, and the call to the entire method is indeed synchronous. Therefore, programming in this way does not take into account the problem of accessing UI controls across threads, which greatly reduces the error rate of asynchronous programming.

Have to say asynchronous programming

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.