一:Task的返回值:
1.使用Task.Result
Task<int> task = Task.Factory.StartNew(()=> {
int s = 0;
for (int i = 0; i < 5; i++)
{
s += i;
}
return s;
});
Console.WriteLine(task.Result);
二:ContinueWith的返回值
Task<int> task = Task.Factory.StartNew(()=> {
int s = 0;
for (int i = 0; i < 5; i++)
{
s += i;
}
return s;
});
var task2 = task.ContinueWith<string>(t =>
{var num = t.Result;
var sum = num + 10;
return sum.ToString();
});
Console.WriteLine(task2.Result);
Console.ReadKey();
三:Task.WhenAll/WhenAny
Task<int> task = Task.Factory.StartNew(() =>
{
return 6;
});
Task<int> task2 = Task.Factory.StartNew(() =>
{
return 2;
});
int[] result = Task.WhenAll<int>(new Task<int>[2] { task, task2 }).Result;
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.ReadKey();
四:异常处理
AggregateException是一个集合,因为task中可能回抛出多个异常,所以我们需要一种新的类型把这些异常都追加到一个集合种
1。什么时候抛出异常?
Task.Wait() or Tresult
2.何时会有多个异常在AggregateException中?
var task = Task.Factory.StartNew(()=> {
var child = Task.Factory.StartNew(() => {
throw new Exception("我是child的异常");
},TaskCreationOptions.AttachedToParent);
var child2 = Task.Factory.StartNew(() => {
throw new Exception("我是child2的异常");
},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().ToString()));
}
}
3.Handle方法,就是处理当前的异常数组,判断上一层我当前哪些已经处理好了,没有处理好的,还需要向上抛出的?
Handle是用来便利异常数组,如果又一个异常信息是这样的,我任务已经处理,如果你觉得异常还需要往上抛,请返回fasle
try
{
task.Wait();
}
catch (AggregateException ex)
{
ex.Handle(x=> {
return true;
});
return false;
}