C # study notes eight threads: async & await entry

    One, involving content

    async & await is introduced in C # 5.0, console output symbol $ is used (string concatenation) C # 6.0 is introduced, its function is similar string.Format () method.

    Second, the connections and differences between the multi-threaded, asynchronous, synchronous

    Kitchen Stories:

    For example, you want to fry a 5-course ABCDE, but only two furnaces can be used, that is, while only two fried dishes. Here, the stove is the thread.

    If the two furnaces are simultaneously fried A and B, that can only wait for the rest of the CDE A or B to start over fried. The waiting process is synchronous , we call blocking , that this time you can only fry A and B, these two dishes.

    If you have a coffee machine, shoving the coffee beans into the water and when you fry A and B of the coffee machine in turn on the switch, then you do not have to leave it there. At this point, is to open a new thread to make coffee, and coffee

Is done automatically by the coffee machine does not affect the continued cooking, making coffee so this thread is asynchronous , which we call non-blocking .

    When the coffee machine sound bite to inform you that the coffee has brewed, the coffee you're going to put out some sugar or milk or something, to get coffee this action we call a callback , this is to inform you that after the completion of the thread coffee to go

Do the action.

    simply put:

    It will take up your time so that you can not do other things, called task synchronization tasks (cooking otherwise it will be focused paste pot).

    Those who do not take up your time task is called asynchronous tasks (coffee brewed coffee will own, you do not need to keep looking at it).

    The following code demonstrates without using asynchronous:

    class Program 
    { 
        // Create a timer 
        Private  static  Readonly The Stopwatch Stopwatch = new new The Stopwatch (); 

        static  void the Main ( String [] args) 
        { 
            #region the async Primer & does not use the await asynchronous
             // starts the timer 
            stopwatch.Start ();
             // the URL of address 
            const  String URL1 = " http://www.cnblogs.com/ " ;
             const  String url2 = " http://www.cnblogs.com/atomy/ " ;
             //An asynchronous download website content, and count the number of characters. 
            var RESULT1 = CountCharacters ( " URL1 " , URL1);
             var result2 = CountCharacters ( " URL2 " , URL2);
             // mainly achieved by splicing string consuming operations 
            for ( var I = 0 ; I < . 3 ; I ++ ) 
            { 
                ExtraOperation (I + . 1 ); 
            } 
            // console output 
            ($ Console.WriteLine " the number of characters of {url1}: RESULT1 {} " ); 
            Console.WriteLine ($ "{url2} number of characters: result2 {} " ); 
            Console.WriteLine ($ " total time stopwatch.ElapsedMilliseconds} MS {. " ); 
            Console.Read (); 
            #endregion 
        } 

        ///  <Summary> 
        // / count the number of characters
         ///  </ Summary> 
        ///  <param name = "ID"> </ param> 
        ///  <param name = "address"> </ param> 
        ///  <Returns> </ returns A> 
        Private  static  int CountCharacters ( String name,string address)
        {
            var wc = new WebClient();
            Console.WriteLine($ " {name} start calling, over {stopwatch.ElapsedMilliseconds} ms, Thread.CurrentThread.ManagedThreadId {} = thread ID. " ); 

            Var Result = wc.DownloadString (address); 
            Console.WriteLine ($ " {name} completed call lasted {stopwatch.ElapsedMilliseconds} ms, Thread.CurrentThread.ManagedThreadId {} = thread ID. " ); 

            return result.Length; 
        } 

        ///  <Summary> 
        /// additional operations
         ///  </ Summary> 
        ///  <param name = "ID"> </ param>
        private static void ExtraOperation(int id)
        {
             // Here are some relatively time consuming operation by concatenating strings
            var S = "" ;
             for ( var I = 0 ; I < 6000 ; I ++ ) 
            { 
                S + = I; 
            } 
            Console.WriteLine ($ " of {id} times ExtraOperation executed, which lasted: {stopwatch.ElapsedMilliseconds} ms. " ); 
        } 
    }
View Code

    Results are as follows:

    The following code demonstrates using asynchronous:

    class Program 
    { 
        // Create a timer 
        Private  static  Readonly The Stopwatch Stopwatch = new new The Stopwatch (); 

        static  void the Main ( String [] args) 
        { 
            #region the async & asynchronous use the await Primer
             // starts the timer 
            stopwatch.Start ();
             / / the URL of address 
            const  String URL1 = " http://www.cnblogs.com/ " ;
             const  String url2 = " http://www.cnblogs.com/atomy/ " ;
             //An asynchronous download website content, and count the number of characters. 
            The Task < int > T1 = CountCharactersAsync ( " URL1 " , URL1); 
            the Task < int > T2 = CountCharactersAsync ( " URL2 " , URL2);
             // primarily by concatenating the string reaches consuming operations 
            for ( var I = 0 ; I < . 3 ; I ++ ) 
            { 
                ExtraOperation (I + . 1 ); 
            } 
            // console output 
            Console.WriteLine ($ " the number of characters of {url1}: {} t1.Result " );
            Console.WriteLine($"{url2} 的字符个数:{t2.Result}");
            Console.WriteLine($"总耗时{stopwatch.ElapsedMilliseconds}ms。");
            Console.Read();
            #endregion
        }

        /// <summary>
        /// 统计字符个数
        /// </summary>
        /// <param name="id"></param>
        /// <param name="address"></param>
        /// <returns></returns>
        private static async Task<int> CountCharactersAsync(string name,was
        {string address)
            = WC new new the WebClient (); 
            Console.WriteLine ($ " {name} begin call lasted {stopwatch.ElapsedMilliseconds} ms, Thread.CurrentThread.ManagedThreadId} {= thread ID. " ); 

            var Result = the await wc.DownloadStringTaskAsync (address ); 
            Console.WriteLine ($ " {name} completed call lasted {stopwatch.ElapsedMilliseconds} ms, Thread.CurrentThread.ManagedThreadId {} = thread ID. " ); 

            return result.Length; 
        } 

        ///  <Summary> 
        // / additional operations
         ///  </ Summary> 
        ///  <param name = "ID"> </ param>
        private static void ExtraOperation ( int ID) 
        { 
            // Here are some relatively time consuming operation by concatenating strings 
            var S = "" ;
             for ( var I = 0 ; I < 6000 ; I ++ ) 
            { 
                S + = I; 
            } 
            Console. the WriteLine ($ " of {id} times ExtraOperation executed, which lasted: {} stopwatch.ElapsedMilliseconds MS. " ); 
        } 
    }
View Code

    Results are as follows:

    Three , async & await structure

    async & await structure may be divided into three parts:

    1) call the method: This method is called asynchronous method, and then continue when the asynchronous method execution of its mandate;

    2) asynchronous method: This method is asynchronous implementation, and then return immediately to the calling method;

    3) await expression: for internal asynchronous method, pointed out that the task should execute asynchronously. The method may comprise a plurality of asynchronous await expressions (expressions do not exist, then await the IDE warn).

    Four , asynchronous method

    Asynchronous Methods: The method returns the call immediately before the execution is complete, complete the task in the process of calling the method continues execution.

    Gramma analysis:

    1) Keywords: head method using async modifier.
    2) Requirements: comprising N (N> 0) th await expression (await expression does not exist will warn IDE), it indicates the need of asynchronous tasks.
    3) Return Type: only 3 types of return (void, Task and the Task <T>). Task and Task <T> object identifier will be returned to complete the work in the future, represents the asynchronous method call methods and can proceed.
    4) Parameter: Any number, but can not use keywords out and ref.
    5) naming conventions: Async method extension should end.

    Reference from:

    https://www.cnblogs.com/woxihuadabai/p/8042652.html

    https://www.cnblogs.com/liqingwen/p/5831951.html

Guess you like

Origin www.cnblogs.com/atomy/p/12038318.html