C # Asynchronous Programming summary __ Programming

Source: Internet
Author: User
Tags instance method
Asynchronous Programming in C # Processes and Threads

The system creates a process in memory when the program is started. A process is a collection of resources required for a program to run, including virtual address space, file handles, and what other programs need to run. Inside the process, the system creates a kernel object called a thread that represents the program that is actually executed. When a thread is established, the system begins executing the thread at the first line of the Main method. About threads: By default, a process consists of only one thread, starting from the program to the end, and the thread can derive other threads, so a process may contain multiple threads of different states, executing different parts of the program, and a process that shares the resources of the process if it contains multiple threads; The planning unit that the processor executes in the system is a thread, not a process. Synchronous and asynchronous synchronization are performed from the order in which the statement appears to complete. Asynchronous refers to statements that do not strictly follow the order in which they appear. Sometimes you need to run a part of the code in a new thread, sometimes without creating a new thread, and in order to improve the efficiency of a single thread, change the order in which the code is executed.

When an operation takes a lot of time to process, if you use synchronous programming, the program will not be able to handle other things in the time it waits for the response, which is inefficient; while using asynchronous programming, the program can use the waiting time to process other things while the response is being answered. Go back to the response and continue, so the program will be more efficient. Synchronous method and asynchronous Method (Async/await)

If a method is invoked, wait for all execution to follow, the method is synchronized, and the asynchronous method returns to the invoked use before the method is finished processing.
Synchronization Method Example:

Class Program {static void Main (string[] args) {mydownloadstring my=new mydownloadstring (); My.

        Dorun ();
    Console.readkey ();

    } class Mydownloadstring {stopwatch sw=new stopwatch ();
        public void Dorun () {const int largenumber = 600000; Sw.
        Start ();
        int T1 = countcharacters (1, "http://www.baidu.com");
        int t2 = countcharacters (2, "https://www.jd.com");
        Counttoalrgenumnber (1,largenumber);
        Counttoalrgenumnber (2,largenumber);
        Counttoalrgenumnber (3,largenumber);
        Counttoalrgenumnber (4,largenumber);
        Console.WriteLine ("Chars in http://www.baidu.com: {0}", T1);
    Console.WriteLine ("Chars in https://www.jd.com: {0}", T2);
        private int countcharacters (int id, string uristring) {WebClient wc1=new WebClient (); Console.WriteLine ("String call {0}: {1, 4} MS", ID,SW.)
        Elapsed.totalmilliseconds); String RESULT=WC1. TodoWnloadstring (New Uri (uristring)); Console.WriteLine ("Call {0} complete: {1, 4} MS", ID, SW.
        Elapsed.totalmilliseconds); return result.
    Length;
        } private void Counttoalrgenumnber (int id,int largernumber) {for (int i = 0; i < Largernumber; i++) {} Console.WriteLine ("End counting{0}: {1,4} ms", ID,SW.)
    Elapsed.totalmilliseconds);  
 }
}

Run Result:

The execution order of the invoked Dorun () method is based on the time sequence of the statement, while the length of the URL character is obtained, the program waits for no other action, and the whole program is executed for: 779.6366ms

Asynchronous Method Example:

 static void Main (string[] args) {Mydownloadstringasync myasync=new mydownloadstringasync ();

        Myasync.dorun ();
    Console.readkey ();

    Class Mydownloadstringasync {Stopwatch SW = new Stopwatch ();
        public void Dorun () {const int largenumber = 600000; Sw.
       Start ();
       Task <int> t1 = countcharacters (1, "http://www.baidu.com");

        task<int> t2 = countcharacters (2, "https://www.jd.com");
        Counttoalrgenumnber (1, largenumber);
        Counttoalrgenumnber (2, Largenumber);
        Counttoalrgenumnber (3, Largenumber);   
        Counttoalrgenumnber (4, Largenumber); Console.WriteLine ("Chars in http://www.baidu.com: {0}", T1.
        result); Console.WriteLine ("Chars in https://www.jd.com: {0}", T2.
    result); Private async task<int> countcharacters (int id, string uristring) {WebClient WC1 = new Webclien
        T ();      Console.WriteLine ("String call {0}"): {1, 4} MS, ID, SW.
        Elapsed.totalmilliseconds); string result = await WC1.
        Downloadstringtaskasync (New Uri (uristring)); Console.WriteLine ("Call {0} complete: {1, 4} MS", ID, SW.
        Elapsed.totalmilliseconds); return result.
    Length; } private void Counttoalrgenumnber (int id, int largernumber) {for (int i = 0; i < Largernumber; i++)
        ; Console.WriteLine ("End counting{0}: {1,4} MS", ID, SW.
    Elapsed.totalmilliseconds);   
 }
}

Run Result:

From the results of the operation, it can be seen that when the Dorun () method is invoked, the order of execution is not based on the timing of the statement, when the

task<int> T1 = countcharacters (1, "http://www.baidu.com");
task<int> t2 = countcharacters (2, "https://www.jd.com");

method, the program returns to the call Place Dorun () method, using the waiting time to execute the subsequent

Counttoalrgenumnber (1, largenumber);
Counttoalrgenumnber (2, largenumber);
Counttoalrgenumnber (3, largenumber);
Counttoalrgenumnber (4, Largenumber); 

Output operation, when the wait is complete, the output gets the length of the URL string, the whole method takes 574.4725ms, and the synchronization method is time consuming 779.6336ms. Visible, asynchronous methods are more efficient. async/await Characteristics

Use the async/await attribute in C # to create an asynchronous method. This feature structure consists of three parts:

Call method

public void Dorun ()
{
...
Task <int> t1 = countcharacters (1, "http://www.baidu.com");
task<int> t2 = countcharacters (2, "https://www.jd.com");
...
} 

The calling method calls an asynchronous method that continues to perform its task while the asynchronous method, possibly on the same thread, might be on the new thread, executes the task.

Asynchronous methods

Private Async  task<int> countcharacters (int id, string uristring)
{
   ...
string result =  await  WC1. Downloadstringtaskasync (New Uri (uristring));
...
return result. Length;
}

Asynchronous method executes the task within the method asynchronously, entering the task at the asynchronous execution, immediately returning to the calling method

Await expression
The await expression indicates the task that needs to be performed asynchronously, and the asynchronous method is returned to the calling method, where the asynchronous task executes, and the method continues to perform its own task. The asynchronous method contains at least one await expression.

A description of the asynchronous method:

The method signature contains the async keyword
Async The keyword is used to indicate that the method contains at least one await expression before the method returns a value, and that keyword does not create any asynchronous tasks.

Asynchronous methods have three return types: the control flow between void,task,task invocation method, and asynchronous Method

The control flow diagram between the calling method and the asynchronous method:


The asynchronous method may contain multiple await statements, and when the asynchronous task created by the last await statement completes, the task's property and return value settings are complete, and the code after the await statement completes synchronously within the asynchronous method, and the asynchronous method executes and exits. await expression

The await expression in the asynchronous method specifies an asynchronous task. This task may or may not be an object of a task type. by default, the task runs asynchronously under the current thread

await task;  

This task is an object of type awaitable, awaitable type is the type of method that implements Getawaiter (), Getawaiter () method returns a Awaiter type Object, and the Awaiter type includes members:
>
-bool Iscompleted{get;}
-void oncompleted (Action);
-void GetResult (); or T getresult ();

In actual use, you do not need to build the awaitable type yourself (just like using yield return to build an enumeration type (enumerable) and an enumerator type (enumerator)), the task class is a awaitable type, Objects that use the task class can create the specified asynchronous task in a await expression. The BCL contains many asynchronous methods that can return the task* Task.run () method

The Task.run () method creates an asynchronous method that differs from the await expression in creating an asynchronous task on the current thread, andTask.run () executes the asynchronous method on another thread
The parameter of the Task.run () method is a delegate that has no arguments, has a return value, and an overload of the Task.run () method:
>
Task Run (Action action);
Task Run (Action action,cancellationtoken token);
Task Run (Func function);
Task Run (Func function,cancellationtoken token);
Task Run (Func function);
Task Run (Func function,cancellationtoken token);
Task Run ( cancellation of Func asynchronous method )

An asynchronous method can terminate an operation. The cancellation of an asynchronous method requires the second parameter type in the Task.run () method-CancellationToken
Cancellation is a class in the System.Threading.Tasks namespace, and the termination of the asynchronous method requires another class under that namespace-CancellationTokenSource
>
Cancellationtokensouce cts=new CancellationTokenSource ();
CancellationToken token=cts. Token; The CancellationTokenSource object creates CancellationToken objects that can be assigned to different tasks. An object holding a CancellationTokenSource can call its Cancel method and set the value of the CancellationToken object's iscancellationrequested to true. The CancellationToken object contains information about whether a task was canceled. Tasks that hold CancellationToken objects need to periodically check their status. If the value of the CancellationToken object's iscancellationrequested is set to True, the task must stop and exit. CancellationToken's iscancellationrequested value setting is not reversible, only once , and once the value is true, it cannot be changed.

It is worth noting that the call to the Cancellationtokensource.cancel () method does not perform an operation to terminate the task. Just set the value of the iscancellationrequested for the CancellationToken object to True. The real termination operation is that the task that holds the CancellationToken object terminates and exits after checking its iscancellationrequested value.
Sample code:
>

Class Program {static void Main (string[] args) {CancellationTokenSource cts=new CancellationTokenSource (
        ); CancellationToken token = cts.
        Token;
        MyClass mc=new MyClass (); Task T=MC.
        Runtask (token);
        Console.WriteLine ("Async Action");
        Thread.Sleep (3000); Cts.
        Cancel ();
        T.wait (); Console.WriteLine ("Was canceled:{0}", token.
        iscancellationrequested);
    Console.readkey ();
    } class MyClass {private stopwatch sw=new stopwatch (); Public async Task Runtask (CancellationToken CT) {if (CT).
        iscancellationrequested) return;
    Await Task.run (() =>cyclemethod (CT), CT); } void Cyclemethod (CancellationToken ct) {sw.
        Start (); Console.WriteLine ("Starting Cyclemethod at time {0,4}", SW.
        Elapsed.totalmilliseconds);
        const int max = 5; for (int i = 0; i < max; i++) {if (CT). iscancellationrequested) returN
            Thread.Sleep (1000); Console.WriteLine ("{0} of {1} iterations completed at time {2,4}", I,MAX,SW.)
        Elapsed.totalmilliseconds);  
 }
    }
}

Run Result:

The following two lines are commented in the preceding code:
>

  Thread.Sleep (3000);   
  Cts. Cancel ();  

Run Result:

When Cancelationtokensource.cancel () is executed, the Iscancelationrequested property value is checked by the Runtask task holding the Cancelationtoken, which is true to end the task and exit. method of Waiting

The wait of the method is divided into waiting in the calling method and waiting in the calling method in the asynchronous method

Any number of asynchronous methods can be invoked within the calling method, you can perform other tasks first, then receive the task object returned by the asynchronous method, or you can wait for the execution of an asynchronous method to finish processing the successor task. You can use the instance method task of a task. Wait () waits for the task. Task. Wait () is for a single Task object, waiting for multiple task objects, and the task class provides two static methods ,Task.waitall (),Task.waitany (), The difference between the two methods is that Task.waitall () waits for all asynchronous methods within the calling method to perform subsequent tasks, while task.waitany () waits for at least one asynchronous task to complete in the calling method , and then perform subsequent tasks without waiting for all the asynchronous methods to finish executing. asynchronous wait in asynchronous methods

Within an asynchronous method, you can wait for a task in an asynchronous method by await an expression, when control returns to the calling method, but within the asynchronous method you can wait for the completion of one or all of the tasks. Implemented by the static method of the Task Task.whenany () and Task.whenall () .
Code Example:

Class Program {static void Main (string[] args) {mydownloadstring mc=new mydownloadstring (); Mc.
        Dorun ();
    Console.readkey (); } class Mydownloadstring {public void Dorun () {task<int> t = Countcharactersasync ("http://www.ba
        Idu.com "," http://www.hao123.com ");
        Console.WriteLine ("Dorun:task{0} finished", t.iscompleted? "": "not");
    Console.WriteLine ("Dorun:result={0}", T.result); Private Async task<int> Countcharactersasync (String str1,string str2) {WebClient wc1=new Webclien
        T ();
        WebClient wc2=new WebClient (); Task<string> t1= WC1.
        Downloadstringtaskasync (New Uri (STR1)); task<string> t2 = WC2.
        Downloadstringtaskasync (New Uri (STR2));
        List<task<string>> tasks=new list<task<string>> (); Tasks.
        ADD (t1); Tasks.
        ADD (T2);
        Await Task.whenany (tasks); Console.WriteLine ("Cca:t1 {0} Completed", T1. IScompleted? "": "not"); Console.WriteLine ("Cca:t2 {0} Completed", T2. IsCompleted?
        "": "not"); return t1. IsCompleted? T1. Result.Length:t2.
    Result.length;  
 }
}

Run Result:

This uses the Whenall () method, which, when executed to the await () in the asynchronous method, returns to the calling method output, completes the asynchronous execution, completes the call to the asynchronous method and returns to the calling method when one of the tasks within the asynchronous method has finished executing. Here the Whenany is changed to Whenall, and the result is:

The WhenAll () method waits for all tasks to be completed inside the asynchronous method before exiting back to the calling method.

About the asynchronous basis first summed up here, there are BeginInvoke () and EndInvoke () and wait-completion, polling, callback and other asynchronous execution mode, interested friends can find their own look

Reference C # Illustrated Tutorial 2012 (fourth edition)

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.