获取Task的返回值
Task<int> task = Task.Factory.StartNew(()=> { return 1; });
task.Wait();
Console.WriteLine(task.Result);
获取ContinueWith的返回值
Task<int> task = Task.Factory.StartNew(()=> { return 1; });
var task2 = task.ContinueWith<int>((t)=>
{
var num = t.Result + 10;
return num;
});
Console.WriteLine(task2.Result);
获取WhenAll/WhenAny的返回值
Task<int> task1 = Task.Factory.StartNew(() => { return 1; });
Task<int> task2 = Task.Factory.StartNew(() => { return 2; });
var tasks = new Task<int>[2] {task1,task2 };
var task = Task.WhenAll<int>(tasks);
int[] result = task.Result;
异常
1.什么时候抛出异常:
Wait操作,TResult操作
2.何时会有多个异常在AggregateException中以及如何去获取所有的异常
AggregateException 是一个集合,因为Task中可能会抛出多个异常,所以用一种新的类型把这些异常都追加到一个集合中。对应以下这段代码:
var task = Task.Factory.StartNew(()=>
{
var childTask1 = Task.Factory.StartNew(() =>
{
throw new Exception("task1 Exception");
}, TaskCreationOptions.AttachedToParent);
var childTask2 = Task.Factory.StartNew(() =>
{
throw new Exception("task2 Exception");
}, TaskCreationOptions.AttachedToParent);
});
try
{
task.Wait();
}
catch (AggregateException ex)
{
foreach (var item in ex.InnerExceptions)
{
Console.WriteLine(string.Format("message={0},type={1}",
item.InnerException.Message, item.GetType().Name));
}
}
3.Handle方法
try
{
try
{
task.Wait();
}
catch (AggregateException ex)
{
ex.Handle(x =>
{
if (x.InnerException.Message == "task1 Exception")
{
return true;
}
return false;
});
}
}
catch (AggregateException ex) { }
当前的Handle就是来遍历异常数组的,如果有一个异常信息是符合要求的,便认为是已经处理的,返回true,如果觉得异常还需要上抛,请返回false。