[Asynchronous programming you must know] -- Task-Based asynchronous mode

Source: Internet
Author: User
Tags apm


I will introduce you to the above two topics. in NET 1.0, APM and. in NET 2.0, when using the previous two modes for asynchronous programming, you may feel more or less difficult to implement. First, it is the task-based asynchronous mode, this mode mainly uses System. threading. tasks. compared with the previous two asynchronous modes, TAP makes the asynchronous programming mode simpler (because we only need to pay attention to the use of the Task class), and TAP is also the asynchronous programming mode recommended by Microsoft, next we will share with you the content of this topic.

Task-based Asynchronous Pattern (TAP) is recommended by Microsoft for its ease of use, the task-based asynchronous mode uses a single method to indicate the start and completion of asynchronous operations. However, the asynchronous programming model (APM) however, the BeginXxx and EndXxx methods are required to indicate the start and completion of asynchronous operations (which is complicated to use). However, the event-based asynchronous mode (EAP) a method with an Async suffix and one or more events, event handlers, and event parameters are required. As you can see, do you all have such a question: how do we distinguish between classes in the. NET class library and implement the task-based asynchronous mode? This recognition method is very simple. When we see that the class has a method with the extension TaskAsync, it indicates that the class implements the TAP,But these two implementations are not as complicated as the implementation in EAP, because if we want to implement the EAP class by ourselves, we need to define the delegate type and event parameters of multiple events and Event Handlers (For details, refer to the BackgroundWorker profiling section in the previous topic), but in the TAP implementation, we only need to pass inCancellationTokenParameter because the IsCancellationRequested attribute of this parameter is monitored inside the Asynchronous Method. When the Asynchronous Method receives a cancel request, the Asynchronous Method will exit execution (you can use the reflection tool to view the WebClient'sDownloadDataTaskAsyncYou can also refer to the subsequent sections to implement the Asynchronous Method Based on the task asynchronous mode .), In the TAP, we can useIProgress <T>For more information about how to implement the progress report function, see the program section below.

After reading the above introduction, can we not wait to know how to implement a task-based Asynchronous Method, in addition, you only need to use this method to cancel asynchronous operations and report progress (because EAP needs to implement other events and define event parameter types, this implementation is not too complex). Next we will use the task-based asynchronous mode to complete the program based on the Program implemented in the previous topic. Next let's implement our own Asynchronous Method (the highlight is that only one method is needed to complete the progress report and Asynchronous Operation cancellation function.):

          DownLoadFile( url, CancellationToken ct, IProgress<>= = =  bufferSize = [] bufferBytes =  = (DownloadSize != == readSize =  (                     (ct.IsCancellationRequested == =>.btnStart.Enabled = .btnPause.Enabled =                         = responseStream.Read(bufferBytes,  (readSize > += percentComplete = ()(()DownloadSize / ()totalSize * =>.btnStart.Enabled = .btnPause.Enabled =                 ex.Handle(e => e 

In this way, we only need the above method to complete the file download program in the previous topic, we only need to call this method in the event handler of the Download button and the event handler of the pause button to call CancellationTokenSource. you can use the Cancel method. The Code is as follows:

                  btnStart_Click(= .btnStart.Enabled = .btnPause.Enabled =             sc == =  Task(() =>                     DownLoadFile(txbUrl.Text.Trim(), ct,  Progress<>(p => SendOrPostCallback((result)=>progressBar1.Value=(          btnPause_Click(

The following describes how the task-based asynchronous mode works and the running result:

After you click OK, the Download button becomes available again. You can click Download to Download again. After the Download is complete, the Download dialog box is displayed. The running result is as follows:

From the above code, we can clearly find that the task-based asynchronous mode is indeed easier to use than the previous two asynchronous modes. NET Framework 4.0, Microsoft recommends using TAP to implement asynchronous programming. This involves how the program previously implemented with APM or EAP is migrated to the implementation with TAP. NET Framwwork also supports the conversion between them.


InSystem. Threading. TasksIn the namespace, there isTaskFactory(Task project) class, which we can useFromAsyncMethod to convert APM to TAP. The following is an example of how to implement the asynchronous programming model in the asynchronous Task-based mode.

Use APM to Implement Asynchronous requests = WebRequest. Create (====++ (webResponse! = Use the FromAsync method to convert APM to TAP = WebRequest. create (<WebResponse> (webRq. beginGetResponse, webRq. endGetResponse, ===+ (ex. getBaseException () + (webResponse! =

The above Code demonstrates the original implementation method of APM and how to use it.FromAsyncThe method converts the implementation method of APM to the implementation method of TAP, and puts the two methods together. One is to help you make a comparison, this makes it easier for you to understand the conversion between APM and TAP. Second, you can also understand the differences between APM and TAP through the comparison above.

Processing APM can be upgraded to using TAP for implementation. For EAP, we can also convert it to TAP. The following Code demonstrates how to convert EAP to TAP:

How to convert EAP to TAP: WebClient webClient = TaskCompletionSource <> tcs = TaskCompletionSource <> webClient. DownloadStringCompleted + = (sender, e) => (e. Error! = Tcs. Task. ContinueWith (t => + webClient. DownloadStringAsync (Uri (

This topic introduces the content of the TAP. This topic describes the simplicity of the task-based asynchronous mode to implement a file download program. in NET 4.0, let's put forward the reason for the TAP. Finally, we will introduce the conversion between the TAP and the APM and EAP modes, through this part, you can clearly understand how the previous asynchronous implementation migrates to the new asynchronous mode, and compare the differences between them from their conversion implementation code. However. in NET 4.5, Microsoft has better support for asynchronous programming-two keywords, async and await, make asynchronous programming as simple as Synchronous Programming, this completely changed the delegate callback and cross-thread access control issues for implementing asynchronous programming. I will introduce this part to you in the next topic.

Download the source code of this topic: http://files.cnblogs.com/zhili/TaskbasedAsynchronousPattern (tapdomain.zip

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.