Developer, Former MVP, now at Microsoft - Best of 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
System.Threading.Tasks.Task
static void WalkTree(Tree tree) { if (tree == null) return; Task left = new Task((o) => WalkTree(tree.Left)); left.Start(); Task righ = new Task((o) => WalkTree(tree.Righ)); righ.Start(); left.Wait(); righ.Wait(); ProcessItem(tree.Data); }
static void Main() { Tree tr = Tree.CreateSomeTree(9, 1); Stopwatch sw = Stopwatch.StartNew(); Task t =Task.StartNew(delegate { WalkTree(tr); }); t.Wait(); Console.WriteLine("Elapsed= " + sw.ElapsedMilliseconds.ToString()); Console.ReadLine(); }
StartNew
ThreadPool.QueueUserWorkItem
Console.WriteLine
WalkTree
left.Wait
righ.Wait
Task.WaitAll(left, right)
WaitAny
Main
Tree tr = Tree.CreateSomeTree(9, 1); Stopwatch sw = Stopwatch.StartNew(); Task t = Task.StartNew(delegate{ WalkTree(tr);});t.ContinueWith(tt => Console.WriteLine("Done"), TaskContinuationKind.OnAny);t.Wait(2500); Console.WriteLine("Elapsed= " + sw.ElapsedMilliseconds.ToString());
ContinueWith
TaskContinuationKind
IsCancellationRequested
IsCanceled
Task
t.ContinueWith(tt => Console.WriteLine("done")); t.Wait(2500); t.Cancel();
...= new Task((o) => WalkTree(tree.Left), TaskCreationOptions.RespectParentCancellation);
TaskCreationOptions.Detached
TaskCreationOptions
static int WalkTree(Tree tree) { if (tree == null) return 0; int left = WalkTree(tree.Left); int righ = WalkTree(tree.Righ); return ProcessItem(tree.Data) + left + righ; }
ProcessItem
WalkTree(righ)
WalkTree(left)
Task<T>
Future<T>
Value
static int WalkTree(Tree tree) { if (tree == null) return 0; Task<int> left = new Task<int>((o) => WalkTree(tree.Left), TaskCreationOptions.RespectParentCanellation); left.Start(); Task<int> righ = new Task<int> ((o) => WalkTree(tree.Righ) , TaskCreationOptions.RespectParentCanellation); righ.Start(); return ProcessItem(tree.Data) + left.Value + righ.Value; }
IsCompleted
AggregateException