//TaskCreationOptions.AttachedToParent不起作用 Task task = Task.Run(() => { var task1 = new Task(() => { Thread.Sleep(1000); Console.WriteLine("11111"); }, TaskCreationOptions.AttachedToParent); task1.Start(); }); task.ContinueWith(t => { Console.WriteLine("222222"); }); task.Wait(); Console.WriteLine("主线程执行完毕");
执行结果:
TaskCreationOptions.AttachedToParent,这里的设置不起作用
//TaskCreationOptions.AttachedToParent起作用 Task task = new Task(() => { var task1 = new Task(() => { Thread.Sleep(1000); Console.WriteLine("11111"); }, TaskCreationOptions.AttachedToParent); task1.Start(); }); task.ContinueWith(t => { Console.WriteLine("222222"); }); task.Start(); task.Wait(); Console.WriteLine("主线程执行完毕");
TaskCreationOptions.AttachedToParent,起到了想要的结果。
通过reflector发现Task.run的底层代码
public static Task Run(Func<Task> function, CancellationToken cancellationToken) { if (function == null) throw new ArgumentNullException(nameof (function)); if (AppContextSwitches.ThrowExceptionIfDisposedCancellationTokenSource) cancellationToken.ThrowIfSourceDisposed(); return cancellationToken.IsCancellationRequested ? Task.FromCancellation(cancellationToken) : (Task) new UnwrapPromise<VoidTaskResult>((Task) Task<Task>.Factory.StartNew(function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default), true); }
其中有TaskCreationOptions.DenyChildAttach,解释了为什么Task.run的 TaskCreationOptions.AttachedToParent为什么无效了