勇哥注:
这篇讨论一下async、await异步编程的异常处理特点。
(一)首先,我们要知道传统的后台线程,你得自己处理异常,否则线程会把异常吐掉
看示例 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
Task.Factory.StartNew(() =>
{
taskfun1();
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
public static void taskfun1()
{
Console.WriteLine("start..");
int a = 5, c = 0;
var k = a / c;
Console.WriteLine("end..");
}
}
}这个例子的输出如下。
可以看到,虽然在调用者main函数里加了try,也捕获不到除零的异常。
也就是说,线程里如果有异常,如果你自己不处理,线程就把异常吐掉了,外面try不到。

你只能自己在线程里处理异常,注意你必须在线程里处理,而不能向上抛(如下面程序中的 throw ex),抛了外面即使有Try也捕获不到。
public static void taskfun1()
{
Console.WriteLine("start..");
try
{
int a = 5, c = 0;
var k = a / c;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//throw ex;
}
Console.WriteLine("end..");
}结果如下:

(二)async异步把异常给你包装好了,可以在调用方(await方法那里)进行捕获。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var f1 = fun2();
Console.ReadKey();
}
public static async Task<int> fun2()
{
try
{
await taskfun2();
return 0;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return 0;
}
public static Task taskfun2()
{
var f1 = Task.Run(() =>
{
Console.WriteLine("start..");
int a = 5, c = 0;
var k = a / c;
Console.WriteLine("end..");
});
return f1;
}
}
}结果如下:

---------------------
作者:hackpig
来源:www.skcircle.com
版权声明:本文为博主原创文章,转载请附上博文链接!


少有人走的路



















