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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With