[C #6] 8-exception enhancement,

Source: Internet
Author: User

[C #6] 8-exception enhancement,
0. Directory

C #6 Add feature catalog

1. Use await in catch and finally Blocks

Introduce a pair of keywords await/async in C #5 to support the new asynchronous programming model, the asynchronous programming model of C # is further simplified (APM-> EAP-> TAP-> await/async. the asynchronous programming model in C # is not the focus of this article, for more information, see Asynchronous Programming Pattern ). Although await/async is introduced in C #5, there are some restrictions. For example, it cannot be used in catch or finally statement blocks. C #6 will not be subject to this restriction.

 1 using System; 2 using System.Threading; 3 using System.Threading.Tasks; 4  5 namespace csharp6 6 { 7     internal class Program 8     { 9         private static void Main(string[] args)10         {11             do12             {13                 Log(ConsoleColor.White, "caller method begin", true);14                 CallerMethod();15                 Log(ConsoleColor.White, "caller method end");16             } while (Console.ReadKey().Key != ConsoleKey.Q);17         }18 19         public static async void CallerMethod()20         {21             try22             {23                 Log(ConsoleColor.Yellow, "try ", true);24                 throw new Exception();25             }26             catch (Exception)27             {28                 Log(ConsoleColor.Red, "catch await begin", true);29                 await AsyncMethod();30                 Log(ConsoleColor.Red, "catch await end");31             }32             finally33             {34                 Log(ConsoleColor.Blue, "finally await begin", true);35                 await AsyncMethod();36                 Log(ConsoleColor.Blue, "finally await end");37             }38         }39 40         private static Task AsyncMethod()41         {42             return Task.Factory.StartNew(() =>43             {44                 Log(ConsoleColor.Green, "async method begin");45                 Thread.Sleep(1000);46                 Log(ConsoleColor.Green, "async method end");47             });48         }49 50         private static void Log(ConsoleColor color, string message, bool newLine = false)51         {52             if (newLine)53             {54                 Console.WriteLine();55             }56             Console.ForegroundColor = color;57             Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");58         }59     }60 }

The running result is as follows:

If you are careful, you will find that the color of async method begin: 6 is not the set green, but white, and the order is also disordered; and you run it again, it may be green. In fact, this is because the two lines of code in the Log method (non-thread-safe method) are called by multiple threads:

1 Console.ForegroundColor = color;2 Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");

We can make some minor changes to ensure the thread security of the Log method (there are many ways to do this in C #, which is only one of them ):

 1 [MethodImpl(MethodImplOptions.Synchronized)] 2 private static void Log(ConsoleColor color, string message, bool newLine = false) 3 { 4     if (newLine) 5     { 6         Console.WriteLine(); 7     } 8     Console.ForegroundColor = color; 9     Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");10 }

It seems to be a bit out of the question. Back to the question, support for await keywords in catch and finally statement blocks does not require support for IL commands or CLR support, instead, it is only the Code Conversion made by the compiler (await/async is the same as that from lambda to delegate ). The specific IL will not be expanded. It is too large. I will paste a picture to see the general situation:

The code we wrote in CallerMethod is transferred to MoveNext. (for more details, refer to the blog of "Dev_Eric", advanced article: Using IL as the sword, async/await) (including the await statements in catch and finally ).

2. Exception Filter

In fact, this language feature has long been supported in VB and F #, and can be used in C #6.

1 try { … }2 catch (Exception e) when (filter(e))3 {4     …5 }

The when part is where the exception filter takes effect, and the when is followed by an expression. If the expression result is true, it enters the current catch statement block.

3. Reference

Asynchronous Programming Patterns

C #6.0 await in catch/finally

C #6.0 Exception filters

Http://www.sadev.co.za/content/exception-filtering-c-6

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.