C# exception enhancement
0. 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 }
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}");
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 }
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
(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
FilterIn 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 }
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:/ /www.php.cn/
The above is the detailed content of C# exception enhancement. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.
