1 回答
TA贡献1859条经验 获得超6个赞
TaskCreationOptions调用时无法指定Task.Run。你需要使用
Task.Factory.StartNew(() => {/*...*/}, TaskCreationOptions.AttachedToParent, default(CancellationToken), TaskScheduler.Default)
顺便说一下,Task.Run默认情况下设置TaskCreationsOptions为DenyChildAttach,因此如果您想要一个子任务,您还需要TaskCreationOptions为父任务指定。所以它看起来像这样:
Task parent = Task.Factory.StartNew(() =>
{
Console.WriteLine("Parent task starting...");
Task child = Task.Factory.StartNew(() =>
{
Console.WriteLine("Child task starting...");
Thread.Sleep(1000);
Console.WriteLine("Child task completed!");
}, TaskCreationOptions.AttachedToParent, default(CancellationToken), TaskScheduler.Default);
}, TaskCreationOptions.None, default(CancellationToken), TaskScheduler.Default);
parent.Wait();
- 1 回答
- 0 关注
- 183 浏览
添加回答
举报