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;
}
