Task class and Async/await

Source: Internet
Author: User
Task class

The Task class is an asynchronous operation abstraction provided after. NET 4.0, and the full path is System.Threading.Tasks.Task.

The task class is used to represent an asynchronous operation with no return value, and a subclass of the task class should be used for asynchronous operations with return values task<tresult>.
Tasks created by the task class are added to the thread pool.

The main constructors of the Task/task<tresult> class are as follows:

Receives the action type as the execution content of the asynchronous Operation public
Task (Action action);
The first parameter is a action<object> type with one parameter, and the second parameter is the content public Task to be passed in
(action<object> Action, Object state);
The TaskCreationOptions type is enumerated and sets the TaskScheduler execution policy public
Task (Action action, taskcreationoptions creationoptions);

Receives the func<tresult> type as the content public
Task (func<tresult> function) that is executed asynchronously in the Task<tresult> class;
Public Task (Func<object, tresult> function, object state);

The created task can start with the start () method:

To add a task to the current TaskScheduler (Task Scheduler), the Task Scheduler chooses the appropriate time to perform the public
void Start ();
Adds a task to the specified TaskScheduler public
void Start (TaskScheduler scheduler);

In actual development, more often than not, use the static method run () of the task class or the member method of the factory class TaskFactory StartNew () to create and start a new task.

Some common methods in the task class:

Queues an asynchronous operation in the parameter in the current scheduler and returns the Task object, public
static task Run (Action action);
public static task<tresult> run<tresult> (func<tresult> function);

Waits for task to complete public
void Wait ();                                                     Waits for the current task to complete the public
static void WaitAll (params task[] tasks);                        Wait for all tasks in the task array to complete public
static bool WaitAll (task[] tasks, int millisecondstimeout;)      /wait for a specified time
async/await keyword

C # 5.0 After the introduction of the async and await keywords, at the language level to provide better concurrency support. Async is used to mark asynchronous methods :
The Async keyword is a contextual keyword that is treated as a keyword only when the method and lambda are decorated, and in other regions will be treated as identifiers. The Async keyword can mark a static method, but it cannot mark the entry point (The Main () method). The method return value of the async tag must be one of the tasks, task<tresult>, void. Await is used to wait for the result of an asynchronous method:
The await keyword is also a contextual keyword and is considered a keyword only in the method of the async tag. The await keyword can be used before the Async method and task, task<tresult>, to wait for the execution of an asynchronous task to end.

A simple async method is structured as follows:

Async Task Testasync ()
{
    ...     Sequentially executed content return

    await Task.run (() =>
    {
        ...     The contents of the asynchronous Execution
    });

It is not the method that uses the Async keyword to mark the asynchronous method, and the statements that appear directly inside the Async method are executed synchronously, and the content that is executed asynchronously needs to be executed using the task class.
In fact, a async method that does not contain any await statements will be executed synchronously, at which point the compiler gives a warning.

A simple example that uses async/await to output content concurrently on the screen:

Using System;
Using System.Threading;

Using System.Threading.Tasks; The function in the class program {//Task.run () method is the content static async task<int> async () => Task that is actually executed asynchronously. Run<int> (() => {//thread ID differs from handler () method Console.WriteLine ("Async () Thr

                EAD ID: [{0}] ", Thread.CurrentThread.ManagedThreadId);
                    for (int i = 0; i < 5; i++) {thread.sleep (100);
                Console.WriteLine ("Async:run{0}", i);
                } Console.WriteLine ("Over");
            return 666;

    }); The Async method that returns a value of void Asynchandler () is only the wrapper static async void Asynchandler () {//the contents of the method body are actually synchronously executed, with the main () function thread ID

        Same Console.WriteLine ("Handler () Thread ID: [{0}]", Thread.CurrentThread.ManagedThreadId);

        Calling asynchronous Method Async () does not block, Async () method begins asynchronous execution of task<int> Task = Async (); Every 0.1s printout, at which point the asynchronous Method Async () is also executed in another thread, and the synchronous print is lostfor (int i = 0; i < 3; i++) {thread.sleep (100);
        Console.WriteLine ("Handler:run{0}", i); The code before using await runs in the same thread Console.WriteLine as the main () function ("Handler1 () threads ID: [{0}]", Thread.currentthrea

        D.managedthreadid);
        The loop in Asynchandler () is executed 3 times, at which point the asynchronous Method async () has not been completed, and the await keyword blocks the function//in the main () function, starting with the call await, and Asynchandler () has returned

        Console.WriteLine (await Task); The code after using await is running the thread Console.WriteLine ("Handler2 () thread ID: [{0}]" in the Async () method, Thread.CurrentThread.ManagedThre

        ADID);
    The print Asynchandler () function actually executes the information Console.WriteLine ("Handler really finished!"); The//Main method cannot be marked as asynchronous static void Main (string[] args) {Console.WriteLine ("Main () Thread ID: [{0}]", THR ead.
        Currentthread.managedthreadid);

        Asynchandler ();

        Prints the information that the Asynchandler () function has finished executing in Main () Console.WriteLine ("Handler finished in main!"); Asynchandler () in practiceBefore the line completes, it needs to block the main thread waiting for the Asynchandler () to actually execute console.readline (); }
}

Output results: (Mono 4.4.0 && archlinux x64)

Main () Thread ID: [1]
Handler () thread ID: [1]
Async () thread ID: [4]
handler:run0
async:run0
Handl Er:run1
async:run1
async:run2
handler:run2
Handler1 () Thread ID: [1]
Handler finished in main!< C10/>async:run3
async:run4
over
666
Handler2 () Thread ID: [4]
Handler really finished!

It is easy to see from the above program that in the asynchronous method of async keyword marking, the code before using await is executed synchronously, and after the await is invoked, the remaining code runs asynchronously on a separate thread.

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.