Process.HasExited returns true even though process is running?

后端 未结 11 2089
忘掉有多难
忘掉有多难 2020-12-15 03:41

I have been observing that Process.HasExited sometimes returns true even though the process is still running.

My code below starts a proces

11条回答
  •  独厮守ぢ
    2020-12-15 04:12

    I would suggest you to try this way:

    process.Start();
    
    while (!process.HasExited)
    {
        // Discard cached information about the process.
        process.Refresh();
    
        // Just a little check!
        Console.WriteLine("Physical Memory Usage: " + process.WorkingSet64.ToString());
    
        Thread.Sleep(500);
    }
    
    foreach (Process current in Process.GetProcessesByName("testprogram"))
    {
        if ((current.Id == process.Id) && !current.HasExited)
            throw new Exception("Oh oh!");
    }
    

    Anyway... in MSDN page of HasExited I'm reading the following hightlighted note:

    When standard output has been redirected to asynchronous event handlers, it is possible that output processing will not have completed when this property returns true. To ensure that asynchronous event handling has been completed, call the WaitForExit() overload that takes no parameter before checking HasExited.

    That could be somehow linked to your problem as you are redirecting everything.

提交回复
热议问题