Simplify asynchronous programming with tasks and simplify asynchronous programming with tasks

Source: Internet
Author: User
Tags apm

Simplify asynchronous programming with tasks and simplify asynchronous programming with tasks
Overview of. Net traditional asynchronous programming

. NET Framework provides the following two standard modes for performing I/O binding and computing binding asynchronous operations:

  • Asynchronous programming model (APM), in which asynchronous operations are represented by a pair of in/End methods (such as FileStream. BeginRead and Stream. EndRead.
  • Event-based asynchronous mode (EAP) in which asynchronous operations are performed by methods/event pairs named "Operation name Async" and "Operation name Completed" (such as WebClient. downloadStringAsync and WebClient. downloadStringCompleted. (EAP is introduced in. NET Framework 2.0 ).
Advantages and functions of tasks

By using the Task object, you can simplify the code and use the following useful functions:

  • After a task is started, you can register the callback as a task continuation at any time.
  • Use the ContinueWhenAll and ContinueWhenAny methods, WaitAll methods, or WaitAny methods to coordinate multiple operations to respond to the Begin _ method.
  • Encapsulate asynchronous I/O binding and computing Binding operations in the same Task object.
  • Monitors the status of the Task object.
  • Use TaskCompletionSource to mail the operation status to the Task object.
Encapsulate common asynchronous programming modes using tasks

1. Use the Task object to encapsulate the APM asynchronous mode. This asynchronous mode is. net standard asynchronous mode. net's oldest asynchronous mode, from. net starts to appear in 1.0, usually by a pair of in/End methods at the same time, take the WebRequest BeginGetResponse and EndGetResponse methods as an example:

var request = WebRequest.CreateHttp(UrlToTest);request.Method = "GET";var requestTask = Task.Factory.FromAsync<WebResponse>(   request.BeginGetResponse,   request.EndGetResponse,   null);requestTask.Wait();var response = requestTask.Result;

2. Use the Task object to encapsulate the EPM asynchronous mode. net 2.0 and is frequently used in Silverlight. This asynchronous mode is characterized by the pairing of the "Operation name Async" function and "Operation name Completed" event, take the DownloadStringAsync method and DownLoadStringCompleted event of WebClient as an example:

var source = new TaskCompletionSource<string>();var webClient = new WebClient();webClient.DownloadStringCompleted += (sender, args) => {   if (args.Cancelled) {      source.SetCanceled();      return;   }   if (args.Error != null) {      source.SetException(args.Error);      return;   }   source.SetResult(args.Result);};webClient.DownloadStringAsync(new Uri(UrlToTest, UriKind.Absolute), null);source.Task.Wait();var result = source.Task.Result;

3. Use the Task object to encapsulate other Non-Standard Asynchronous modes. This mode is frequently used in third-party class libraries and is usually called back using an Action parameter. The following method is used as an example:

void AddAsync(int a, int b, Action<int> callback)

The encapsulation method is similar to the encapsulation of the mime asynchronous mode:

var source = new TaskCompletionSource<int>();Action<int> callback = i => source.SetResult(i);AddAsync(1, 2, callback);source.Task.Wait();var result = source.Task.Result;

The preceding example shows that asynchronous operations are much simpler after the asynchronous operations are encapsulated by the Task object. You can directly obtain the results of asynchronous operations by calling the Wait method of the Task, instead of going to the callback function for processing, let's look at a more practical example.

Buffer query example

Taking the buffer query provided by Esri as an example, you can select a suitable point on the map, query the buffer zone based on a certain radius, and then query the relevant building information in the buffer zone. In this example, we need to perform two interactions with the server:

This example is very simple and typical in GIS Query. The ESRI example also provides the complete source code. The core logic code of this example is:

_ GeometryService = new GeometryService (GeoServerUrl); _ geometryService. bufferCompleted + = GeometryService_BufferCompleted; _ queryTask = new QueryTask (QueryTaskUrl); _ queryTask. executeCompleted + = QueryTask_ExecuteCompleted; void MyMap_MouseClick (object sender, Map. mouseEventArgs e) {// part of the code is omitted and the buffer query _ geometryService starts. bufferAsync (bufferParams);} void GeometryService_BufferCompleted (object sender, GraphicsEventArgs args) {// some code is omitted to obtain the buffer query result and start querying the Building Information _ queryTask in the buffer zone. executeAsync (query);} void QueryTask_ExecuteCompleted (object sender, QueryEventArgs args) {// update the query result to the interface}

This is just a simple query in GIS development. The above code disperses the logic in three functions. In actual application, more interactions are performed with the server, the Code logic is dispersed in more functions, reducing the readability and maintainability of the Code. If you use a Task object to encapsulate these tasks, the entire logic will be much simpler. GeometryService and QueryTask provide the mime asynchronous mode. The corresponding encapsulation methods are shown above. Finally, the code for encapsulating asynchronous operations with tasks is as follows:

Void MyMap_MouseClick (object sender, Map. mouseEventArgs e) {Task. factory. startNew () => {// omit Part Of The UI code and start buffering query var bufferParams = new BufferParameters () {/* initialize the buffer query parameter */}; var bufferTask = _ geometryService. createBufferTask () // wait for the buffer query result bufferTask. wait (); // omitting the updated UI code to start querying the building information in the buffer zone var query = new Query () {/* initialize the query parameter */}; var queryExecTask = _ queryTask. createExecTask (query); queryExecTask. wait (); // display the query result on the interface, Code omitted });}

From the code above, we can see that the logic originally dispersed in three functions can be concentrated in one function by using the Task object. the readability and maintainability of the Code are much higher than the original one.

More tasks can be completed by tasks, such as parallel computing and coordination of multiple concurrent tasks. If you are interested, read the relevant MSDN documents.

The above motion graphs are provided by "Graph dado ".

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.