c# - TaskCreationOptions.AttachedToParent 不等待子任务

标签 c# async-await

根据 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) 的代码通常不使用 AttachedToParentAttachedToParent 是任务并行库 (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/

相关文章:

C# LINQ "inner join"集合

c# - 是否可以在 C# 中使用无类型泛型列表?

c# - basic 中 string$ 的 C# 等价物是什么

asp.net - 哪些 ASP.NET 生命周期事件可以是异步的?

.net - 异步方法在哪里运行?

c# - session 变量无法更新

c# - HashSet UnionWith AddIfNotPresent 死锁

c# - 异步和并行执行函数

c# - 对一次性对象使用 Await Async WhenAll

c# - 拦截通过 DynamicProxy 返回通用 Task<> 的异步方法