I have to say asynchronous programming. I Have To Say asynchronous programming.

Source: Internet
Author: User

I have to say asynchronous programming. I Have To Say asynchronous programming.

1. What is asynchronous programming?

Asynchronous programming puts time-consuming operations into a separate thread for processing (this thread needs to reflect the execution progress to the interface ). Since time-consuming operations are executed in another thread, it does not block the main thread. After the main thread starts these separate threads, it can continue to perform other operations (such as form drawing ).

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

 

2. asynchronous programming model (APM)

APM is short for Asynchronous Programming Mode, that is, the meaning of the Asynchronous Programming model. It allows the program to execute more operations with fewer threads. In. NET Framework, to determine whether a class has implemented an asynchronous programming model, we mainly need to check whether the class has implemented the BeginXXX method and EndXXX method that return the IAsyncResult interface.

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

2.1 Beginxxx Method -- start to execute asynchronous operations

When you need to obtain the content of a file, we usually use the FileStream synchronization method Read to Read the content. The definition of this synchronization method is as follows:

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

When the preceding method is used to read the content of a large file, the UI thread is blocked, leading to the problem that the file content is not completely read, you cannot perform any operations on the form (including closing the application). In this case, the form cannot respond.

To solve this problem, Microsoft proposed the asynchronous programming model as early as. NET 1.0, and provided the asynchronous mode implementation for the FileStream class, that is, the BeginRead method. This method performs the read operation asynchronously and returns the object that implements the IAsyncResult interface (the object stores the information of this asynchronous operation ).

The definition of the BeginRead method is given below. We can find out the difference between it and the synchronization 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 three parameters of the asynchronous method are the same as those of the synchronous method Read, and the last two parameters userCallback and StateObject are not available in the synchronous method. UserCallback indicates the method to be called back after the asynchronous operation is complete. This method must match the AsyncCallback delegate type. stateObject indicates the object passed to the callback method. In the callback method, you can query the AsyncState attribute of the IAsyncResult interface to read this object. This asynchronous method does not block the UI thread because after it is called, it immediately returns the control to the calling thread (if the UI thread calls this method, then the control is returned to the UI thread), and the other thread executes the file read operation.

 

2.2 Endxxx Method -- end Asynchronous Operation

Each time you call the Beginxxx method, the application also needs to call the Endxxx method to obtain the results returned by the operation. The Beginxxx method returns an object that implements the IAsyncResult interface. This object is not the result returned by the corresponding synchronization method. In this case, you also need to call the Endxxx method to end asynchronous operations and pass the objects returned by Beginxxx to this method. The Endxxx method returns the same type as the synchronization method. For example, the FileStream EndRead method returns an Int32 type, representing the actual number of bytes read from the file stream.

There are many methods to call the Endxxx method, but one is the most commonly used one is to use the AsyncCallback delegate to specify the method to be called when the operation is completed, call the Endxxx method in the callback method to obtain the result returned by the asynchronous operation.

 1 static void Main() 2 { 3     SynchronizationContext sc=SynchronizationContext.Current; 4     AsyncMethodCaller methodCaller=new AsyncMethodCaller(DownLoadFileAsync); 5     method.BeginInvoke(txtUrl.Text.Trim(),GetResult,null); 6 } 7 private static void GetRsult(IAsyncResult result) 8 { 9     AsyncMethodCaller caller=(AsyncMethodCaller)((AsyncResult)result).AsyncDelegate;10     string returnstring=call.EndInvoke(result);11 }

 

3. asynchronous programming model (EAP)

Although the previous asynchronous programming can solve the problem that the interface cannot respond when time-consuming operations are executed, APM also has these obvious problems, for example, canceling asynchronous operations and downloading progress reports are not supported. However, for desktop applications, the progress report and cancellation functions are essential. NET 2.0 released a new Asynchronous programming model-Event-based Asynchronous programming model (EAP ).

The EAP class has one or more methods suffixed with Async and corresponding Completed events, and these classes support canceling asynchronous methods and progress reports. In the. NET class library, only partial categories implement EAP, a total of 17. Among the 17 classes, the BackgroundWorker class is the most used during development.

Frequently Used attributes are:

CancellationPending: Used to indicate whether the application has requested to cancel background operations;

IsBusy: indicates whether the asynchronous operation is running;

WorkReportProgress: indicates whether the BackgrounWorker can report the progress;

Workersuppscanscancellation: Indicates whether BackgroundWoker supports asynchronous cancellation;

Frequently used methods:

CancelAsync: cancels asynchronous operations;

ReportProgress: used to raise the ProgressChanged event;

RunWorkAsync: starts asynchronous operations after the call;

The following three events are frequently used:

DoWork: events triggered when RunWokerAsync is called;

ProgressChanged: The event triggered when ReportProgress is called. The program updates the progress report in this event;

RunWorkerCompleted: triggered when the asynchronous operation is completed, canceled, or exception is thrown.

This method is rarely used, so we will not detail it here.

 

4. What is TAP?

The two asynchronous programming modes provided by. NET are respectively APM in. NET 1.0 and EAP in. NET 2.0. Although the two asynchronous programming modes can implement asynchronous programming in most cases, they are marked as not recommended in the MSDN document, because in. in NET 4.0, Microsoft also provides a simpler asynchronous programming implementation method-TAP, a task-based asynchronous mode.

This mode uses the Task <T> class in the System. Threading. Tasks namespace to implement asynchronous programming. Therefore, before using TAP, you must first introduce the System. Threading. Tasks namespace.

The Task-based Asynchronous mode (TAP, Task-based Asynchronous Pattern) only uses one method to indicate the start and completion of Asynchronous operations, however, APM requires the Beginxxx and Endxxx methods to indicate the start and end, respectively. EAP requires a method suffixed with Async and one or more events. In the task-based asynchronous mode, you only need a method suffixed with TaskAsync. By passing the CancellationToken parameter to this method, we can complete asynchronous programming well. You can also use the IProgress <T> interface to implement the progress report function. In general, using TAP will reduce our workload and make the code more concise.

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

 

5. Make async and await in So easy -- C #5.0 in asynchronous programming

Although. NET 1.0 and. NET 2.0 and. NET 4.0 has made great support for asynchronous programming, and Microsoft has gradually made it easier to use asynchronous programming. However, Microsoft feels that the existing work is not enough, it is designed to simplify the development process of asynchronous programming. in NET 4.5, Microsoft proposed async and await to support asynchronous programming.

This is also the simplest asynchronous programming implementation method in the. NET Framework. Because the two keywords are used for asynchronous programming, the thinking method is exactly the same as the Synchronous Programming Method.

The async and await keywords do not allow the calling method to run in the new thread, but divide the method into multiple fragments (the fragment's boundaries appear at the position where the await keyword is used inside the method ), and some fragments can be run asynchronously. The code snippet at the await keyword is run on the thread pool thread, and the call of the entire method is indeed synchronized. Therefore, you do not need to consider cross-thread access to the UI control, which greatly reduces the error rate of 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.