[C #] entering the asynchronous programming world,

Source: Internet
Author: User

[C #] entering the asynchronous programming world,
Going into the world of asynchronous programming-analyzing asynchronous methods (II)

 

Collation

Thanks for your support. This is a supplement to "going into the world of asynchronous programming-analyzing asynchronous methods (I)" published yesterday.

 

Directory
  • Exception Handling
  • Synchronously wait for a task in the call Method
  • Waiting for tasks asynchronously in asynchronous Methods
  • Task. Delay () pause execution

  

I. Exception Handling

The await expression can also use the try... catch... finally structure.

1 internal class Program 2 {3 private static void Main (string [] args) 4 {5 var t = DoExceptionAsync (); 6 t. wait (); 7 8 Console. writeLine ($ "{nameof (t. status) }:{ t. status} "); // task Status 9 Console. writeLine ($ "{nameof (t. isCompleted) }:{ t. isCompleted} "); // task completion status id 10 Console. writeLine ($ "{nameof (t. isFaulted) }:{ t. isFaulted} "); // whether the task has an unhandled exception ID 11 12 Console. read (); 13} 14 15 /// <summary> 16 // exception operation 17 /// </s Ummary> 18 // <returns> </returns> 19 private static async Task DoExceptionAsync () 20 {21 try22 {23 await Task. run () =>{ throw new Exception () ;}); 24} 25 catch (Exception) 26 {27 Console. an exception occurred in WriteLine ($ "{nameof (DoExceptionAsync! "); 28} 29} 30}

Figure 1-1

[Analysis] The await expression is located in the try block, and the exception is handled in a normal way. However, why are the Status, IsCompleted, and IsFaulted displayed in the figure respectively: RanToCompletion, True) and not failed (False? Because: The task has not been canceled and all exceptions have been handled!

 

2. Wait for the task synchronously in the call Method

To call a method, you may need to wait for a special Task object to complete at a certain time point before executing the subsequent code. In this case, you can use the instance method Wait.

1 internal class Program 2 {3 private static void Main (string [] args) 4 {5 var t = CountCharactersAsync ("http://www.cnblogs.com/liqingwen/"); 6 7 t. wait (); // Wait until the task ends 8 Console. writeLine ($ "Result is {t. result} "); 9 10 Console. read (); 11} 12 13 // <summary> 14 // count the number of characters 15 /// </summary> 16 // <param name = "address"> </param> 17 // <returns> </returns> 18 private static async Task <int> CountCharactersAsync (string address) 19 {20 var result = await Task. run () => new WebClient (). downloadStringTaskAsync (address); 21 return result. length; 22} 23}

Figure 2-1

 

Wait () is suitable for a single Task object. If you want to operate a group of objects, you can use the two static methods WaitAll () and WaitAny () of the Task ().

1 internal class Program 2 {3 private static int time = 0; 4 private static void Main (string [] args) 5 {6 var t1 = GetRandomAsync (1 ); 7 var t2 = GetRandomAsync (2); 8 9 // ID of the IsCompleted Task 10 Console. writeLine ($ "t1. {nameof (t1.IsCompleted) }:{ t1.IsCompleted}"); 11 Console. writeLine ($ "t2. {nameof (t2.IsCompleted) }:{ t2.IsCompleted}"); 12 13 Console. read (); 14} 15 16 /// <summary> 17 // obtain a random number 18 /// </summary> 19 /// <param name = "id"> </param> 20 // <returns> </returns> 21 private static async Task <int> GetRandomAsync (int id) 22 {23 var num = await Task. run () => 24 {25 time ++; 26 Thread. sleep (time * 100); 27 return new Random (). next (); 28}); 29 30 Console. writeLine ($ "{id} finished calling"); 31 return num; 32} 33}

Figure 2-2 The IsCompleted attribute of both tasks shows incomplete

 

Now, add two lines of code (lines 6 and 7) to the Main () method and try to call the WaitAll () method.

1 private static void Main (string [] args) 2 {3 var t1 = GetRandomAsync (1); 4 var t2 = GetRandomAsync (2 ); 5 6 Task <int> [] tasks = new Task <int> [] {t1, t2}; 7 Task. waitAll (tasks); // wait until all tasks are completed before continuing to execute the 8 9 // IsCompleted task to complete the identification 10 Console. writeLine ($ "t1. {nameof (t1.IsCompleted) }:{ t1.IsCompleted}"); 11 Console. writeLine ($ "t2. {nameof (t2.IsCompleted) }:{ t2.IsCompleted}"); 12 13 Console. read (); 14}

Figure 2-3 The IsCompleted attribute of both tasks is displayed as True.

 

Now, change row 7th again and call the WaitAny () method.

1 private static void Main (string [] args) 2 {3 var t1 = GetRandomAsync (1); 4 var t2 = GetRandomAsync (2 ); 5 6 Task <int> [] tasks = new Task <int> [] {t1, t2}; 7 Task. waitAny (tasks); // wait until any Task is completed before continuing to execute 8 9 // IsCompleted Task completion mark 10 Console. writeLine ($ "t1. {nameof (t1.IsCompleted) }:{ t1.IsCompleted}"); 11 Console. writeLine ($ "t2. {nameof (t2.IsCompleted) }:{ t2.IsCompleted}"); 12 13 Console. read (); 14}

Figure 2-4 The IsCompleted attribute of a task is displayed as True (finished) and continues execution.

 

3. Waiting for tasks asynchronously in asynchronous Methods

The above section describes how to use WaitAll () and WaitAny () to synchronously wait for the Task to complete. This time, we use Task. WhenAll () and Task. WhenAny () to asynchronously wait for the Task in the Asynchronous Method.

1 internal class Program 2 {3 private static int time = 0; 4 5 private static void Main (string [] args) 6 {7 var t = GetRandomAsync (); 8 9 Console. writeLine ($ "t. {nameof (t. isCompleted) }:{ t. isCompleted} "); 10 Console. writeLine ($ "Result: {t. result} "); 11 12 Console. read (); 13} 14 15 /// <summary> 16 // obtain a random number 17 /// </summary> 18 /// <param name = "id"> </param> 19 /// <returns> </returns> 20 private static async Task <int> GetRandomAsync () 21 {22 time ++; 23 var t1 = Task. run () => 24 {25 Thread. sleep (time * 100); 26 return new Random (). next (); 27}); 28 29 time ++; 30 var t2 = Task. run () => 31 {32 Thread. sleep (time * 100); 33 return new Random (). next (); 34}); 35 36 // wait asynchronously until all tasks in the set are completed before proceeding to the Next step 37 await Task. whenAll (new List <Task <int> () {t1, t2}); 38 39 Console. writeLine ($ "t1. {nameof (t1.IsCompleted) }:{ t1.IsCompleted}"); 40 Console. writeLine ($ "t2. {nameof (t2.IsCompleted) }:{ t2.IsCompleted}"); 41 42 return t1.Result + t2.Result; 43} 44}

Figure 3-1 call the WhenAll () method

[Note] WhenAll () waits for tasks in the set to be completed asynchronously and does not occupy the Time of the main thread.

 

Now, we replace the WhenAll () method in the GetRandomAsync () method with WhenAny () and increase the thread suspension time. The final modification is as follows:

1 private static async Task <int> GetRandomAsync () 2 {3 time ++; 4 var t1 = Task. run () => 5 {6 Thread. sleep (time * 100); 7 return new Random (). next (); 8}); 9 10 time ++; 11 var t2 = Task. run () => 12 {13 Thread. sleep (time * 500); // here it is changed from 100 to 500, otherwise the effect 14 return new Random () will not be displayed (). next (); 15}); 16 17 // wait asynchronously until all tasks in the set are completed before proceeding to the Next step 18 // await Task. whenAll (new List <Task <int> () {t1, t2}); 19 await Task. whenAny (new List <Task <int> () {t1, t2}); 20 21 Console. writeLine ($ "t1. {nameof (t1.IsCompleted) }:{ t1.IsCompleted}"); 22 Console. writeLine ($ "t2. {nameof (t2.IsCompleted) }:{ t2.IsCompleted}"); 23 24 return t1.Result + t2.Result; 25}

Figure 3-2 call the WhenAny () method

 

Iv. Task. Delay () pause execution

The Task. Delay () method creates a Task object, which suspends processing in the thread and completes after a certain period of time. Unlike Thread. Sleep, it does not block the Thread, meaning the Thread can continue to process other work.

 1     internal class Program 2     { 3         private static void Main(string[] args) 4         { 5             Console.WriteLine($"{nameof(Main)} - start."); 6             DoAsync(); 7             Console.WriteLine($"{nameof(Main)} - end."); 8  9             Console.Read();10         }11 12         private static async void DoAsync()13         {14             Console.WriteLine($"    {nameof(DoAsync)} - start.");15 16             await Task.Delay(500);17 18             Console.WriteLine($"    {nameof(DoAsync)} - end.");19         }20     }

Figure 4-1

 

Portal

Getting Started: getting started with async/await asynchronous programming

Article 1: going into the world of asynchronous programming-analyzing asynchronous methods (I)

 

Http://www.cnblogs.com/liqingwen/p/5866241.html.

[Reference] Illustrated C #2012

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.