开了控制台跑如下代码,断点跑到task1.Result就没了,也没有进task1那个return 3 的方法。请问为什么呢?
static void Main(string[] args)
{
try
{
var task1 = new Task<int>(() => { return 3; });
var task2 = new Task<int>(() => { throw new KeyNotFoundException(); return 3; });
var result1 = task1.Result;
var result2 = task2.Result;
}
catch (AggregateException e) when (e.InnerExceptions.FirstOrDefault().GetType() == typeof(KeyNotFoundException))
{
}
}
把 new Task
改为 Task.Run
class Program
{
static void Main(string[] args)
{
try
{
var task1 = Task.Run(() => { return 3; });
var task2 = Task.Run(() => { throw new KeyNotFoundException(); return 3; });
var result1 = task1.Result;
var result2 = task2.Result;
}
catch (AggregateException e)
when (e.InnerExceptions.FirstOrDefault().GetType() == typeof(KeyNotFoundException))
{
throw e;
}
}
}
如果不使用 Task.Run ,需要调用 Task.Start 方法。
class Program
{
static void Main(string[] args)
{
try
{
var task1 = new Task<int>(() => { return 3; });
var task2 = new Task<int>(() => { throw new KeyNotFoundException(); return 3; });
task1.Start();
task2.Start();
var result1 = task1.Result;
var result2 = task2.Result;
}
catch (AggregateException e)
when (e.InnerExceptions.FirstOrDefault().GetType() == typeof(KeyNotFoundException))
{
throw e;
}
}
}