TaskCreationOptions.AttachedToParent不等待子任务 [英] TaskCreationOptions.AttachedToParent is not waiting for child task

查看:1335
本文介绍了TaskCreationOptions.AttachedToParent不等待子任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据MSDN:

您可以使用AttachedToParent选项前preSS结构任务
  并行,因为父任务隐式地等待所有子
  任务完成。

You can use the AttachedToParent option to express structured task parallelism, because the parent task implicitly waits for all child tasks to finish.

所以我有这个code:

So I have this code:

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。

I would like to know why the time is 0 and not 1000.

推荐答案

$ C $使用基于任务的异步模式(TAP)C不能正常使用 AttachedToParent AttachedToParent 是任务的设计的一部分并行库(TPL)。无论是TPL和TAP共享相同的工作键入,但也有应TAP code可以避免很多TPL成员。

Code that uses the Task-based Asynchronous Pattern (TAP) does not normally use AttachedToParent. AttachedToParent was part of the design of the Task Parallel Library (TPL). Both the TPL and TAP share the same Task type, but there are many TPL members that should be avoided in TAP code.

在TAP,可以支持父和具有父异步方法子异步方法的概念等待任务从孩子回来异步方法:

In TAP, you can support the notion of "parent" and "child" async methods by having the "parent" async method await the task returned from the "child" async method:

public async Task<int> GetIntAsync()
{
  var childTask = Task.Run(() =>
  {
    ...
    await Task.Delay(1000);
    ...
  });
  ...

  await childTask;
  return 1;
}

这篇关于TaskCreationOptions.AttachedToParent不等待子任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆