private static void TestTask1() { Console.WriteLine("start TestTask1====="); Task task1 = new Task(() => { Thread.Sleep(3000); Console.WriteLine($"..thread1 run..threadid={Thread.CurrentThread.ManagedThreadId}"); }); task1.Start(); Task task2 = new Task(() => { Thread.Sleep(2000); Console.WriteLine($"..thread2 run..threadid={Thread.CurrentThread.ManagedThreadId}"); }); task2.ContinueWith((o) => { Console.WriteLine($"thread2 finished.... threadid={Thread.CurrentThread.ManagedThreadId}"); }); task2.Start(); Console.WriteLine("end TestTask1====="); }
运行结果:
start TestTask1===== end TestTask1===== ..thread2 run..threadid=5 thread2 finished.... threadid=6 ..thread1 run..threadid=4
private static void TestTask2() { Console.WriteLine("start TestTask2........"); TaskFactory taskFactory = new TaskFactory(); List<Task> tasks = new List<Task>(); tasks.Add(taskFactory.StartNew(() => { Thread.Sleep(2000); Console.WriteLine("..thread1.."); })); tasks.Add(taskFactory.StartNew(() => { Thread.Sleep(1800); Console.WriteLine("..thread2.."); })); tasks.Add(taskFactory.StartNew(() => { Thread.Sleep(1600); Console.WriteLine("..thread3.."); })); taskFactory.ContinueWhenAll(tasks.ToArray(), (t) => { Console.WriteLine("all finished......"); }); Console.WriteLine("end TestTask2........"); }
运行结果:
start TestTask2........
end TestTask2........
..thread3..
..thread2..
..thread1..
all finished......