Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a Process has started but not yet exited?

I have some code that creates a Process instance and later starts it. There's some logic that need to check if the Process has been started. HasExited can be used to check if a started process has been exited, but I can not find a similar function for HasStarted. At first glance StartTime looked like a good option, but this function will throw if the process has exited. Also, the documentation says that StartTime only has meaning for started processes.

What is the "correct" approach for determining if a process has started (has been started, but might have quit)?

like image 807
larsmoa Avatar asked Dec 06 '22 15:12

larsmoa


1 Answers

While the methods suggested by others will work, it is not the most efficient way to handle such things. If you keep a loop checking whether the Process has exited or not, you will waste a lot of system resources. Your concern should be to just know when the process is exiting, and not sit looping for it to check whether it has exited. So, the correct way is to handle Events.

The code below explains how to do that using Events.

// Declare your process object with WithEvents, so that events can be handled.
private Process withEventsField_MyProcess;
Process MyProcess {
    get { return withEventsField_MyProcess; }
    set {
        if (withEventsField_MyProcess != null) {
            withEventsField_MyProcess.Exited -= MyProcess_Exited;
        }
        withEventsField_MyProcess = value;
        if (withEventsField_MyProcess != null) {
            withEventsField_MyProcess.Exited += MyProcess_Exited;
        }
    }
}

bool MyProcessIsRunning;
private void Button1_Click(System.Object sender, System.EventArgs e)
{
    // start the process. this is an example.
    MyProcess = Process.Start("Notepad.exe");

    // enable raising events for the process.
    MyProcess.EnableRaisingEvents = true;

    // set the flag to know whether my process is running
    MyProcessIsRunning = true;
}

private void MyProcess_Exited(object sender, System.EventArgs e)
{
    // the process has just exited. what do you want to do?
    MyProcessIsRunning = false;
    MessageBox.Show("The process has exited!");
}

EDIT: Knowing whether the process has started or not should be easy since are starting the process somewhere in the code. So you can set a flag there and set it to false when the process is exiting. I updated the code above to show how such a flag can be set easily.

like image 84
Pradeep Kumar Avatar answered Dec 28 '22 22:12

Pradeep Kumar