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

Source: Internet
Author: User
Tags apm

Summary of this topic

  • Introduction

  • What is TAP-Introduction to task-based asynchronous mode

  • How to use TAP -- use the task-based asynchronous mode for asynchronous programming

  • Can TAP be converted to APM or EAP? -- Convert from other asynchronous Modes

  • Summary


I. Introduction

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 of all, I personally think that when using APM, first, we need to define the delegate used to wrap the callback method, which is a little complicated. However, when using EAP, we need to implement the Completed event and Progress event, both of the above implementation methods are a bit cumbersome, and Microsoft has also realized this, so in. NET 4.0 introduces a new asynchronous mode-Task-Based asynchronous mode, which 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.

Ii. What is TAP-Introduction to task-based asynchronous mode

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 EAP mode is required) 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 TaskAsync is a Suffix in a class, it indicates that the class implements the TAP,In addition, the task-based asynchronous mode also supports canceling asynchronous operations and reporting progress. However, these two implementations are not as complex as those implemented in EAP, if we want to implement the EAP class by ourselves, we need to define the delegate types and event parameters of multiple events and Event Handlers (For details, refer to the BackgroundWorker profiling section in the previous topic ), however, in the TAP implementation, we only need to passCancellationTokenParameter 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.

Currently, I have not found. NET class library implements the task-based asynchronous mode of which class provides the progress report function, the following will show you this implementation, and is also the highlight of this program, at the same time, we can further understand the task-based asynchronous mode by implementing the Asynchronous Method of TAP.

Iii. How to use TAP -- use the asynchronous mode based on tasks for asynchronous programming

After reading the above introduction, can we not wait to know how to implement a task-based Asynchronous Method, in addition, you only need 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 you only need one method to complete the progress report and Asynchronous Operation cancellation function.):

// Download File // CancellationToken parameter value assignment get a cancel request // The progress parameter is responsible for the progress report private void DownLoadFile (string url, CancellationToken ct, IProgress <int> progress) {HttpWebRequest request = null; HttpWebResponse response = null; Stream responseStream = null; int bufferSize = 2048; byte [] bufferBytes = new byte [bufferSize]; try {request = (HttpWebRequest) webRequest. create (url); if (DownloadSize! = 0) {request. addRange (DownloadSize);} response = (HttpWebResponse) request. getResponse (); responseStream = response. getResponseStream (); int readSize = 0; while (true) {// exit the asynchronous operation if (ct. isCancellationRequested = true) {MessageBox. show (String. format ("Download paused. The download URL is {0} \ n. The number of downloaded bytes is {1}", downloadPath, DownloadSize); response. close (); filestream. close (); SC. post (state) => {this. btnStart. enabled = true; this. btnPause. enabled = false ;}, null); // exit the asynchronous break;} readSize = responseStream. read (bufferBytes, 0, bufferBytes. length); if (readSize> 0) {DownloadSize + = readSize; int percentComplete = (int) (float) DownloadSize/(float) totalSize * 100); filestream. write (bufferBytes, 0, readSize); // report progress. report (percentComplete);} else {MessageBox. show (String. format ("download completed, the download address is {0}, the total number of bytes of the file is: {1} bytes", downloadPath, totalSize); SC. post (state) => {this. btnStart. enabled = false; this. btnPause. enabled = false ;}, null); response. close (); filestream. close (); break ;}} catch (aggresponexception ex) {// The OperationCanceledException exception will be thrown when the Cancel method is called. // any OperationCanceledException object is treated as processing ex. handle (e => e is OperationCanceledException );}}

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:

// Start DownLoad File private void btnStart_Click (object sender, EventArgs e) {filestream = new FileStream (downloadPath, FileMode. openOrCreate); this. btnStart. enabled = false; this. btnPause. enabled = true; filestream. seek (DownloadSize, SeekOrigin. begin); // capture the synchronization context derived object SC = SynchronizationContext of the call thread. current; cts = new CancellationTokenSource (); // use the specified operation to initialize a new Task. Task = new Task () => Actionmethod (cts. Token), cts. Token); // start the Task and schedule it to the current TaskScheduler for execution. Task. start (); // await DownLoadFileAsync (txbUrl. text. trim (), cts. token, new Progress <int> (p => progressBar1.Value = p);} // method executed in the task private void Actionmethod (CancellationToken ct) {// use the Post method of the synchronized text to update the UI so that the main thread executes DownLoadFile (txbUrl. text. trim (), ct, new Progress <int> (p => {SC. post (new SendOrPostCallback (result) => progressBar1.Value = (int) result), p) ;}// Pause Download private void btnPause_Click (object sender, EventArgs e) {// issue a cancel request cts. cancel ();}

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

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1619433038-0.jpg "style =" margin: 0px; padding: 0px; border: 0px; "/>

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:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1619432145-1.png "style =" margin: 0px; padding: 0px; border: 0px; "/>

4. can TAP be converted to APM or EAP? -- Convert from other asynchronous Modes

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.

4.1 convert APM to TAP

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.

// You can compare the two implementation methods # region uses APM to implement asynchronous request private void APMWay () {WebRequest webRq = WebRequest. Create (" http://msdn.microsoft.com/zh-CN/ "); WebRq. beginGetResponse (result => {WebResponse webResponse = null; try {webResponse = webRq. endGetResponse (result); Console. writeLine ("request content size:" + webResponse. contentLength);} catch (WebException ex) {Console. writeLine ("exception occurred, exception information:" + ex. getBaseException (). message);} finally {if (webResponse! = Null) {webResponse. close () ;}}, null) ;}# endregion # region use the FromAsync method to convert APM to TAP private void APMswitchToTAP () {WebRequest webRq = WebRequest. create (" http://msdn.microsoft.com/zh-CN/ "); Task. factory. fromAsync <WebResponse> (webRq. beginGetResponse, webRq. endGetResponse, null, TaskCreationOptions. none ). continueWith (t => {WebResponse webResponse = null; try {webResponse = t. result; Console. writeLine ("request content size:" + webResponse. contentLength);} catch (aggresponexception ex) {if (ex. getBaseException () is WebException) {Console. writeLine ("exception occurred, exception information:" + ex. getBaseException (). mes Sage) ;}else {throw ;}} finally {if (webResponse! = Null) {webResponse. Close () ;}}) ;}# endregion

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.

4.2 convert EAP to TAP

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 region converts EAP to TAP // The webClient class supports event-based asynchronous mode (EAP) WebClient webClient WebClient = new webClient (); // create TaskCompletionSource and its underlying Task object TaskCompletionSource <string> tcs = new TaskCompletionSource <string> (); // after a string is downloaded, The WebClient object will send the DownloadStringCompleted event webClient. downloadStringCompleted + = (sender, e) =>{ // the following code is executed on the GUI thread // sets the Task status if (e. error! = Null) {// try to set basic Tasks. task <TResult> to Tasks. taskStatus. faulted status tcs. trySetException (e. error);} else if (e. cancelled) {// try to set basic Tasks. task <TResult> to Tasks. taskStatus. canceled status tcs. trySetCanceled ();} else {// try to set basic Tasks. task <TResult> is converted to TaskStatus. ranToCompletion status. Tcs. trySetResult (e. result) ;}}; // when the Task is completed, the following Task continues and the status of the Task is displayed. // to make the following Task run on the GUI thread, it must be marked as TaskContinuationOptions. executeSynchronously // without this flag, the task code will run tcs on a thread pool thread. task. continueWith (t => {if (t. isCanceled) {Console. writeLine ("Operation canceled");} else if (t. isFaulted) {Console. writeLine ("exception occurred, exception information:" + t. exception. getBaseException (). message);} else {Console. writeLine (String. format ("Operation completed, result: {0}", t. result) ;}}, TaskContinuationOptions. executeSynchronously); // starts asynchronous webClient operations. downloadStringAsync (new Uri (" http://msdn.microsoft.com/zh-CN/ "); # Endregion
V. Summary

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.



This article is from the "LearningHard" blog, please be sure to keep this source http://learninghard.blog.51cto.com/6146675/1200926

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.