Parent task does not wait for child task to complete

前端 未结 3 1951
北海茫月
北海茫月 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 parent = Task.Factory.StartNew(() =>
            {
                var results = new int[3];
    
                TaskFactory factory = new TaskFactory(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);
            }
        }
    

提交回复
热议问题