Parent task does not wait for child task to complete

前端 未结 3 1949
北海茫月
北海茫月 2021-01-12 08:28

So here is my code

Task parent = Task.Run(() =>
{
    var result = new int[3];

    TaskFactory tf = new TaskFactory(TaskCreationOptions.Atta         


        
相关标签:
3条回答
  • 2021-01-12 08:58

    Please use the code as below:

    static void RunParentTask()
        {
            Task<int[]> parent = Task.Factory.StartNew<int[]>(() =>
            {
                var results = new int[3];
    
                TaskFactory<int> factory = new TaskFactory<int>(TaskCreationOptions.AttachedToParent,
                                                                TaskContinuationOptions.ExecuteSynchronously);
                factory.StartNew(() => results[0] = 1);
                factory.StartNew(() => results[1] = 2);
                factory.StartNew(() => results[2] = 3);
    
                return results;
            });
    
            parent.Wait();
    
            foreach (var item in parent.Result)
            {
                Console.WriteLine(item);
            }
        }
    
    0 讨论(0)
  • 2021-01-12 09:01

    In Task.Run's documentation, you'll find that it specifies

    Its CreationOptions property value is TaskCreationOptions.DenyChildAttach.

    So, even though you specify TaskCreationOptions.AttachedToParent, it is ignored.

    0 讨论(0)
  • 2021-01-12 09:05

    This behaviour is due to your use of the Task.Run method, which forbids child tasks from being attached to the parent:

    The Run method is a simpler alternative to the StartNew method. It creates a task [whose] CreationOptions property value is TaskCreationOptions.DenyChildAttach.

    To resolve, simply change your first line from

    Task<int[]> parent = Task.Run(() =>
    

    to

    Task<int[]> parent = Task.Factory.StartNew(() =>
    
    0 讨论(0)
提交回复
热议问题