Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TaskCreationOptions.AttachedToParent is not waiting for child task

Tags:

c#

async-await

According to MSDN:

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

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();  
}

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

like image 743
MuriloKunze Avatar asked Jan 04 '13 02:01

MuriloKunze


People also ask

What is the difference between attached and detached child tasks?

A child task can be either detached or attached. A detached child task is a task that executes independently of its parent. An attached child task is a nested task that is created with the TaskCreationOptions.

How does task Wait work?

Wait is a synchronization method that causes the calling thread to wait until the current task has completed. If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread.

What is task factory StartNew in C#?

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.


1 Answers

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.

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;
}
like image 178
Stephen Cleary Avatar answered Oct 21 '22 00:10

Stephen Cleary