这两个参数类用在创建Task和ContinueWith()中
TaskCreationOptions:
TaskCreationOptions.AttachedToParent:子任务执行完后,父任务才会继续执行。否则父任务不会等子任务执行完成
Task t = new Task(() => { var t1 = new Task(() => { Thread.Sleep(1000); Console.WriteLine("t1 end"); }, TaskCreationOptions.AttachedToParent); var t2 = new Task(() => { Thread.Sleep(1000); Console.WriteLine("t2 end"); }, TaskCreationOptions.AttachedToParent); t1.Start(); t2.Start(); }); t.Start(); t.Wait(); Console.WriteLine("主线程end"); //输出结果 t1 end、t2 end、主线程end
TaskCreationOptions.DenyChildAttach:不允许子任务附加到当前任务
Task t = new Task(() => { var t1 = new Task(() => { Thread.Sleep(1000); Console.WriteLine("t1 end"); }, TaskCreationOptions.AttachedToParent); var t2 = new Task(() => { Thread.Sleep(1000); Console.WriteLine("t2 end"); }, TaskCreationOptions.AttachedToParent); t1.Start(); t2.Start(); }, TaskCreationOptions.DenyChildAttach); t.Start(); t.Wait(); Console.WriteLine("主线程end"); //输出结果 主线程end、t1 end、t2 end
TaskCreationOptions.HideScheduler:子任务默认不使用父任务的Scheduler,而是使用默认的
TaskCreationOptions.LongRunning:如果你知道任务是长时间运行,就使用此选项,不使用TreadPool
TaskCreationOptions.PreferFairness:队列?
TaskContinuationOptions:
TaskCreationOptions中有的属性它都有,就不介绍了
TaskContinuationOptions.LazyCancellation:cancell延时执行,默认情况下在执行ContinueWith方法中就判断cancell状态。加上此选项后,在Action中判断cancell状态
var tokenSource = new CancellationTokenSource(); tokenSource.Cancel(); Task t1 = new Task(() => { Thread.Sleep(1000); Console.WriteLine("t1 end"); }); var t2 = t1.ContinueWith((t) => { Thread.Sleep(1000); Console.WriteLine("t2 end"); }, tokenSource.Token,TaskContinuationOptions.LazyCancellation,TaskScheduler.Current); var t3 = t2.ContinueWith((t) => { Console.WriteLine("t3 end"); }); t1.Start(); //执行结果:t1 end、t3 end //如果不加TaskContinuationOptions.LazyCancellation,执行结果是:t3 end、t1 end
TaskContinuationOptions.ExecuteSynchronously:延续任务使用之前任务的线程执行
//TaskContinuationOptions.OnlyOnCanceled:只有在之前任务取消,才执行
//TaskContinuationOptions.OnlyOnFaulted:只有在之前任务异常,才执行
//TaskContinuationOptions.OnlyOnRanToCompletion:只有在之前任务正常完成,才执行
//TaskContinuationOptions.NotOnCanceled:只有在之前任务没取消,才执行
//TaskContinuationOptions.NotOnFaulted:只有在之前任务没异常,才执行
//TaskContinuationOptions.NotOnRanToCompletion:只有在之前任务没正常完成,才执行