Task启动的几种方式
var task = new Task(() => { Console.WriteLine("工作线程" + Thread.CurrentThread.ManagedThreadId); }); task.Start(); //工厂 Task.Factory.StartNew(() => { Console.WriteLine("工作线程" + Thread.CurrentThread.ManagedThreadId); }); Task.Run(() => { Console.WriteLine("工作线程" + Thread.CurrentThread.ManagedThreadId); }); //同步的方式 task = new Task(() => { Console.WriteLine("工作线程" + Thread.CurrentThread.ManagedThreadId); }); //阻塞执行 task.RunSynchronously();Task阻塞方式和延续操作
下面开启2个线程
Task task = new Task(() => { Thread.Sleep(500); Console.WriteLine("工作线程1 " + DateTime.Now.ToString()); }); task.Start(); Task task1 = new Task(() => { Console.WriteLine("工作线程2 " + DateTime.Now.ToString()); }); task1.Start();WaitAll
//需要等待所有线程执行完毕,才会继续执行主线程 Task.WaitAll(task, task1 ); Console.WriteLine("主线程" + Thread.CurrentThread.ManagedThreadId); Console.ReadLine();WaitAny
//只要有一个Task执行完毕,就算完成,继续走主线程 Task.WaitAny(task, task1); Console.WriteLine("主线程" + Thread.CurrentThread.ManagedThreadId); Console.ReadLine();ContinueWith 不阻塞主线程,等两个线程执行完毕之后,执行延续任务
//WhenAll 将task和task1执行完毕之后,在执行延续任务ContinueWith Task.WhenAll(task, task1).ContinueWith(t => { Console.WriteLine("延续任务"); }); //WhenAll 执行完一个线程之后就开始执行延续任务 Task.WhenAny(task, task1).ContinueWith(t => { Console.WriteLine("延续任务"); }); Console.WriteLine("主线程" + Thread.CurrentThread.ManagedThreadId); Console.ReadLine();Task工厂中的延续操作
Task.Factory.ContinueWhenAll(new Task[2] { task, task1 }, (t) => { Console.WriteLine("延续任务"); }); Task.Factory.ContinueWhenAny(new Task[2] { task, task1 }, (t) => { Console.WriteLine("延续任务"); });