Unity - A计划(永久有效期) 扫二维码继续学习 二维码时效为半小时

(197评价)
价格: 4431.00元
C# 线程 Task 父任务与子任务问题
JexFong发起了问答2021-07-22
1
回复
630
浏览
    使用一个任务开启线程,这个任务中再开启一个子任务,然而理论上父任务会在子任务结束之后,状态才会变为
RunToCompletion,子任务结束之前因该为WaitingForChildrenToComplete,然而我写出的代码运行后没有等待子任务的状
态,直接父任务结束之后父任务状态就变为RunToCompletion,没有父子任务关联了。难道现在C#去掉父子任务了嘛


源码:
private static void Example10()
{
    _parentTaskCheck = true;
    var parent = new Task(Example10_ParentTask);
    parent.Start();
    while (_parentTaskCheck)
    {
        
        Console.WriteLine("parent task status: " + parent.Status);
        Thread.Sleep(500);
    }

    Console.WriteLine(parent.Status==TaskStatus.WaitingForChildrenToComplete);
}

private static void Example10_ParentTask()
{
    Console.WriteLine("parent task is running.");
    var child = new Task(Example10_ChildTask);
    child.Start();
    Thread.Sleep(1000);
    Console.WriteLine("parent task is over.");
}

private static bool _parentTaskCheck;
private static void Example10_ChildTask()
{
    Console.WriteLine("child task is running.");
    Thread.Sleep(5000);
    Console.WriteLine("child task is over.");
    _parentTaskCheck = false;
}
输出结果:

parent task is running.
parent task status: WaitingToRun
child task is running.
parent task status: Running
parent task is over.
parent task status: Running
parent task status: RanToCompletion
parent task status: RanToCompletion
parent task status: RanToCompletion
parent task status: RanToCompletion
parent task status: RanToCompletion
parent task status: RanToCompletion
parent task status: RanToCompletion
child task is over.
RanToCompletion


 

所有回复
发表回复
你还没有登录,请先 登录或 注册!