Task.Wait(),Task.Result都調用InternalWait方法spa
Task.WhenAll<TResult>()code
Task.WhenAny<TResult>()blog
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 it
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; }