[C#6] 8-异常增强

时间:2021-09-25 16:17:35

0. 目录

C#6 新增特性目录

1. 在catch和finally块中使用await

在C#5中引入一对关键字await/async,用来支持新的异步编程模型,使的C#的异步编程模型进一步的简化(APM->EAP->TAP->await/async,关于C#中的异步编程模型的不是本篇文章的介绍重点,详细的资料请移步这里Asynchronous Programming Pattern)。在C#5中虽然引入了await/async,但是却有一些限制,比如不能再catch和finally语句块中使用,C#6中将不再受此限制。

 using System;
using System.Threading;
using System.Threading.Tasks; namespace csharp6
{
internal class Program
{
private static void Main(string[] args)
{
do
{
Log(ConsoleColor.White, "caller method begin", true);
CallerMethod();
Log(ConsoleColor.White, "caller method end");
} while (Console.ReadKey().Key != ConsoleKey.Q);
} public static async void CallerMethod()
{
try
{
Log(ConsoleColor.Yellow, "try ", true);
throw new Exception();
}
catch (Exception)
{
Log(ConsoleColor.Red, "catch await begin", true);
await AsyncMethod();
Log(ConsoleColor.Red, "catch await end");
}
finally
{
Log(ConsoleColor.Blue, "finally await begin", true);
await AsyncMethod();
Log(ConsoleColor.Blue, "finally await end");
}
} private static Task AsyncMethod()
{
return Task.Factory.StartNew(() =>
{
Log(ConsoleColor.Green, "async method begin");
Thread.Sleep();
Log(ConsoleColor.Green, "async method end");
});
} private static void Log(ConsoleColor color, string message, bool newLine = false)
{
if (newLine)
{
Console.WriteLine();
}
Console.ForegroundColor = color;
Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");
}
}
}

运行结果如下:

[C#6] 8-异常增强

如果你细心的话会发现async method begin:6这一行的颜色居然不是我设置的绿色,而是白色,而且顺序也出现了错乱;而你再运行一次,它可能就是绿色了。这其实是由于我在Log方法(非线程安全的方法)里面的两行代码被多个线程争抢调用引起的:

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

我们可以做点小改动来让Log方法做到线程安全(在C#中有很多方式可以做到,这只是其中一种):

 [MethodImpl(MethodImplOptions.Synchronized)]
private static void Log(ConsoleColor color, string message, bool newLine = false)
{
if (newLine)
{
Console.WriteLine();
}
Console.ForegroundColor = color;
Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");
}

貌似有点跑题了,回归正题,在catch和finally语句块中支持await关键字并不需要IL指令的支持,也不需要CLR的支持,而仅仅是编译器做出的代码转换(await/async就像lambda一样到delegate一样)。具体的IL就不做展开了,太庞大了,贴个图看下大致的情况:

[C#6] 8-异常增强

我们在CallerMethod中所写的代码,被转移到MoveNext中(更详细的资料请移步园友"Dev_Eric"的一篇博客:进阶篇:以IL为剑,直指async/await)(包括catch和finally中的await语句)。

2. 异常过滤器

其实这个语言特性在VB,F#里面早就支持了,现在C#6里面也可以使用了。

 try { … }
catch (Exception e) when (filter(e))
{

}

其中when这一块就是异常过滤器生效的地方,when后面跟一个表达式,表达式结果如果为true,则进入当前catch语句块。

3. 参考

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