Home > Software engineering >  Example code for getting task status WaitingForChildrenToComplete
Example code for getting task status WaitingForChildrenToComplete

Time:02-28

Please give an example code for getting task status WaitingForChildrenToComplete. I made an example as I was thinking, but it does not give the desired status.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            void MyMethod1()
            {
                Console.WriteLine("MyMethod1");
            }

            void MyMethod2(Task task)
            {
                Console.WriteLine("MyMethod2");
                Task MyTask = new Task(() => { Thread.Sleep(1000); Console.WriteLine(task.Status); }, TaskCreationOptions.AttachedToParent);
                MyTask.Start();
                Thread.Sleep(5000);                
            }
            
            Task MyTask = null;
            MyTask = Task.Run(() => MyMethod2(MyTask));
            MyTask.Wait();
        }
    }
}

CodePudding user response:

Here is an example:

using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        Task parent = Task.Factory.StartNew(() =>
        {
            Task child = Task.Factory.StartNew(() => Thread.Sleep(200),
                TaskCreationOptions.AttachedToParent);
        });
        Thread.Sleep(100);
        Console.WriteLine($"Status: {parent.Status}");
    }
}

Output:

Status: WaitingForChildrenToComplete

Try it on Fiddle.

The reason that your example doesn't work is because the Task.Run method is a shortcut for the Task.Factory.StartNew configured with the TaskCreationOptions.DenyChildAttach option. You can read about this here.

Note: The example above is intended to be minimal, and so it doesn't follow best practices. Particularly the Task.Factory.StartNew method is not configured with a specific scheduler, which is not recommended, and might produce compiler warnings. Also be aware that the "attach to parent" functionality is rarely used today. AFAIK it was deemed a suspicious pattern by Microsoft itself shortly after its introduction, and today many Microsoft engineers would be glad to go back in time and un-invent this feature, if traveling back in time was possible.

  • Related