根据 MSDN:
You can use the AttachedToParent option to express structured task parallelism, because the parent task implicitly waits for all child tasks to finish.
所以我有这段代码:
public async Task<int> GetIntAsync()
{
var childTask = Task.Factory.StartNew(async () =>
{
await Task.Delay(1000);
},TaskCreationOptions.AttachedToParent);
return 1;
}
public async Task<ActionResult> Index()
{
var watch = Stopwatch.StartNew();
var task = GetIntAsync();
var result = await task;
var time = watch.ElapsedMilliseconds;
return View();
}
我想知道为什么时间是0而不是1000。
最佳答案
使用基于任务的异步模式 (TAP) 的代码通常不使用 AttachedToParent
。 AttachedToParent
是任务并行库 (TPL) 设计的一部分。 TPL 和 TAP 共享相同的 Task
类型,但 TAP 代码中应避免使用许多 TPL 成员。
在 TAP 中,您可以通过让“父”异步方法等待
从“子”异步方法返回的任务来支持“父”和“子”异步方法的概念:
public async Task<int> GetIntAsync()
{
var childTask = Task.Run(() =>
{
...
await Task.Delay(1000);
...
});
...
await childTask;
return 1;
}
关于c# - TaskCreationOptions.AttachedToParent 不等待子任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14150448/