Home > Backend Development > C#.Net Tutorial > C# exception enhancement

C# exception enhancement

PHPz
Release: 2017-03-12 15:45:50
Original
1291 people have browsed it

0. Catalog

C#6 NewFeature Catalog

1. In the catch and finally blocks Using await

introduces a pair of keywords await/async in C#5 to support the new asynchronousProgramming model, making C# asynchronous programming The model is further simplified (APM->EAP->TAP->await/async. The asynchronous programming model in C# is not the Introduction focus of this article. For detailed information, please go here Asynchronous Programming Pattern). Although await/async was introduced in C#5, it has some restrictions. For example, it cannot be used in catch and finally statement blocks. This restriction will no longer apply in C#6.


 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 }
Copy after login

The running results are as follows:

If you are careful, you will find thatasync method begin:6The color of this line is not the green I set, but white, and the order is also out of order; if you run it again, it may be green. This is actually caused by the two lines of code in my Log method (non-thread safe method) being called by multiple threads:

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

We can make some small changes to make the Log method thread-safe (there are many ways to do it in C#, this is just 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 }
Copy after login

It seems a little off topic, back to the topic, supporting the await keyword in the catch and finally statement blocks does not require the support of the IL instruction, nor the support of the CLR, but is just the code conversion made by the compiler (await/async is like Same as lambda to delegate). I won’t expand the specific IL, it’s too huge. Here’s a picture to see the general situation:

The code we wrote in CallerMethod was transferred to Move

Next

(For more detailed information, please visit a blog of garden friend "Dev_Eric": Advanced article: Using IL as a sword, pointing directly to async/await) (including the await statements in catch and finally ). 2. Exception

Filter

In fact, this language feature has been supported in VB and F# for a long time, and now it can also be used in C#6.

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

The when section is where the exception filter takes effect. When is followed by an expression

. If the expression result is true, enter The current catch statement block. 3. Reference

Asynchronous Programming Patterns

C# 6.0 await in catch/finally

C# 6.0 Exception filters

http:/ /m.sbmmt.com/

The above is the detailed content of C# exception enhancement. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c#
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template