Task<TResult>,带返回值的Task
Task.Wait(),Task.Result都调用InternalWait方法
Task.WhenAll<TResult>()
Task.WhenAny<TResult>()
public static void DoSomething()
{
Task<int> task1 = Task.Factory.StartNew(() =>
{
//做一些逻辑运算
return 1;
});
Task<int> task2 = Task.Factory.StartNew(() =>
{
//做一些逻辑运算
return 2;
});
var task = Task.WhenAll<int>(new Task<int>[2] { task1, task2 }).ContinueWith(x =>
{
//do something
});
}
异常处理
AggregateException
try
{
Task<int> t = Task.Factory.StartNew(() =>//这里不要使用Task.Run方法,它默认DenyChildAttach
{
Task t1 = Task.Factory.StartNew(() =>
{
throw new Exception("exception 1");
}, TaskCreationOptions.AttachedToParent);
Task t2 = Task.Factory.StartNew(() =>
{
throw new Exception("exception 2");
}, TaskCreationOptions.AttachedToParent);
return 1;
});
try
{
t.Wait();
}
catch (AggregateException ex)
{
ex.Handle(x =>//handle方法遍历AggregateException ,ex1返回true处理完成,ex2返回false会放到新的异常聚集里向上抛出
{
if (x.InnerException.Message.Contains("1"))
return true;
return false;
});
throw;
}
}
catch (AggregateException ex)//AggregateException 中只剩exception2了
{
throw;
}

浙公网安备 33010602011771号