Implement Task-Based asynchronous mode and Task asynchronous mode

Source: Internet
Author: User
Tags net thread

Implement Task-Based asynchronous mode and Task asynchronous mode
Return to the "Task-Based asynchronous mode-Overview" Generation Method compiler generation in this series of directories

In. NET Framework 4.5, the C # compiler implements TAP. Any method marked with the async keyword is an Asynchronous Method. the compiler uses the TAP to execute the necessary conversions to implement the method asynchronously. This method should return the Task or Task <TResult> type. In the latter case, the method body should return a TResult, And the compiler will ensure that the returned Task <TResult> is usable. Similarly, unprocessed exceptions in the method body will be blocked and sent to the output task, resulting in the returned Task ending with Faulted. If OperationCanceledException (or derived type) is not processed, the returned Task ends in the Canceled state.

Manually generated

Developers can manually implement the TAP, just like the compiler or better control the implementation of the method. The compiler dependency comes from System. threading. the public surface area exposed by the Tasks namespace (and created in System. threading. task. runtime. types supported by CompilerServices), as well as functions directly available to developers. When manually implementing the TAP method, the developer must ensure that the returned Task is completed when the asynchronous operation is complete.

Hybrid Generation

The implementation of the mixed core logic in the implementation generated by the compiler is usually useful for manual implementation of the TAP. For example, in this case, to avoid exceptions directly generated by the method caller rather than exposed by the Task, such:

public Task<int> MethodAsync(string input){    if (input == null) throw new ArgumentNullException("input");    return MethodAsyncInternal(input);}private async Task<int> MethodAsyncInternal(string input){    … // code that uses await}

The parameter should change outside the asynchronous method generated by the compiler. Another useful scenario of this delegate is that when a "express connect" optimization can be achieved by returning a cached task.

Workload

Asynchronous operations with limited computing and limited I/O can be implemented using the TAP method. However, when the implementation of TAP is exposed from a database, it should only provide the workload that contains I/O operations (they can also include computing, but should not only include computing ). If a method is purely restricted by computing, it should be exposed only through one asynchronous implementation, the consumer can then choose whether to package the call of the synchronous method into a Task to unload the Task to other threads, and/or to implement parallelism.

Computing restrictions

The Task class is most suitable for computing-intensive operations. By default, in order to provide effective execution operations, it uses special support from the. Net thread pool, and provides a lot of control over how to execute asynchronous computing at and wherever.

There are several ways to generate a task with computing limitations.

Consider the following Asynchronous Method for rendering images. The task body can obtain the cancellation token. When rendering occurs, the Code may exit prematurely if a withdrawal request arrives. Moreover, if a withdrawal request occurs before the rendering starts, we can also block any rendering.

public Task<Bitmap> RenderAsync(    ImageData data, CancellationToken cancellationToken){    return Task.Run(() =>    {        var bmp = new Bitmap(data.Width, data.Height);        for(int y=0; y<data.Height; y++)        {            cancellationToken.ThrowIfCancellationRequested();            for(int x=0; x<data.Width; x++)            {                … // render pixel [x,y] into bmp            }        }        return bmp;    }, cancellationToken);}

If at least one of the following conditions is correct, the restricted tasks end with a Canceled state:

If another unhandled exception exists in the Task body, the Task will end with a Faulted state, at the same time, any attempt or access to the task will cause an exception.

I/O restrictions

Tasks created using TaskCompletionSource <TResult> cannot be directly returned by all executed threads. TaskCompletionSource <TResult> exposes the Task attribute of a returned Task <TResult> instance. The life cycle of a task is controlled by the method exposed by the TaskCompletionSource <TResult> instance. In other words, these instances include SetResult, SetException, SetCanceled, and their TrySet * variables.

Think about this requirement and create a task that will be completed after a specific time. For example, this may be useful when a developer wants to delay an activity for a period of time in the UI scenario .. . NET. threading. the Timer class already provides this ability to call a delegate asynchronously after a specific period of time. In addition, we can use TaskCompletionSource <TResult> to place a Task on the timer. For example:

public static Task<DateTimeOffset> Delay(int millisecondsTimeout){    var tcs = new TaskCompletionSource<DateTimeOffset>();    new Timer(self =>    {        ((IDisposable)self).Dispose();        tcs.TrySetResult(DateTimeOffset.UtcNow);    }).Change(millisecondsTimeout, -1);    return tcs.Task;}

In. Net 4.5, Task. Delay () is generated for this purpose. For example, such a method can be used inside another Asynchronous Method to implement an asynchronous round training loop:

public static async Task Poll(    Uri url,     CancellationToken cancellationToken,     IProgress<bool> progress){    while(true)    {        await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);        bool success = false;        try        {            await DownloadStringAsync(url);            success = true;        }        catch { /* ignore errors */ }        progress.Report(success);    }}

No non-generic copy of TaskCompletionSource <TResult>. However, the Task <TResult> is derived from the Task. Therefore, the generic TaskCompletionSource <TResult> can be used for methods with limited I/O, they all use a fake TResult source (Boolean is the default choice. If the developer is concerned with the consumer of the Task in the downward transformation of the Task, a private TResult type can be used) returns only one Task. For example, the developed Delay method aims to return the current time along the generated Task <DateTimeOffset>. If such a result value is unnecessary, the method can be replaced by the following code (note that the return type is changed and the TrySetresult parameter is changed ):

public static Task Delay(int millisecondsTimeout){    var tcs = new TaskCompletionSource<bool>();    new Timer(self =>    {        ((IDisposable)self).Dispose();        tcs.TrySetResult(true);    }).Change(millisecondsTimeout, -1);    return tcs.Task;}
Tasks with mixed computing restrictions and I/O restrictions

Asynchronous methods are not limited by computing restrictions or I/O restrictions, but can represent a mixture of the two. In fact, multiple asynchronous operations of different nature are combined to generate larger hybrid operations. For example, consider the previous RenderAsync method. This method performs a computation intensive operation based on input ImageData to render an image. The ImageData may come from a Web service that we access asynchronously:

public async Task<Bitmap> DownloadDataAndRenderImageAsync(    CancellationToken cancellationToken){    var imageData = await DownloadImageDataAsync(cancellationToken);    return await RenderAsync(imageData, cancellationToken);}

This example also shows how a separate CancellationToken is threaded through multiple asynchronous operations.

Return to the Task-based asynchronous mode in this series of directories-Overview

Author: tkb to simple source: http://www.cnblogs.com/farb/

QQ: 782762625

You are welcome to discuss more!

The copyright of this article is shared by the author and the blog Park. You are welcome to reprint it. Without the consent of the author, the original article link and author must be clearly marked on the article page; otherwise, the legal liability is reserved.
If you think this article is good or rewarding, click[Recommended]Button, because your support is the greatest motivation for me to continue writing and share!

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.