Default TaskCreationOptions task in Task.Run

Why is the default value for CreationOptions for Task created using Task.Run DenyChildAttach and not None ?

This is due to the fact that to simplify the work with the new async and await in C # 5.0 (not allowing to avoid escaping the current scheduler of the current context)?

+6
source share
2 answers

Steven Tuub explains this well in his related blog post .

Parent and child tasks are often used when using Task in parallel. Note that when the parent Task has a child, the semantics of parent completion change subtly.

Parent / child tasks are almost never used when using Task in async . In the async world, you have a kind of โ€œlogical relationship between parents and childrenโ€ when one async method calls another, but it is not really implemented using parent / child tasks.

Typically, a Task intended for use in async code does not expect the semantics of its completion to be altered by a child task attached to it. Thus, the new default value for Task.Run is DenyChildAttach , which prevents any child tasks from trying.

+7
source

Why is the default value for CreationOptions of a task created using Task.Run a DenyChildAttach and not None?

There are no parameters (default or others) when creating a task using the Task.Run Method .

Quoting from Task.Run vs Task.Factory.StartNew (by Stephen Toub - MSFT) :

  • Task.Run "should just be seen as a quick way to use Task.Factory.StartNew without having to specify a bunch of parameters. Its shortcut"
  • Task.Run(someAction); exactly equivalent to:

     Task.Factory.StartNew ( someAction , CancellationToken.None , TaskCreationOptions.DenyChildAttach , TaskScheduler.Default ); 
  • "Thus, Task.Run can and should be used for the most common cases."

MSDN article Nested Tasks and Child Tasks (for .NET 4.0 , i.e. without any equivalents for C # 5.0 / .NET 4.5):

โ€œin most scenarios, we recommend using nested tasks because relationships with other tasks are less complicated. That's why tasks created inside other tasks are nested by default, and you must explicitly specify the AttachedToParent parameter to create a child taskโ€

which explains why CreationOptions.DenyChildAttach was chosen for the shortest most common and simplest option.

+3
source

Source: https://habr.com/ru/post/944776/


All Articles