David Bentley
David Bentley

Reputation: 864

Can EnableRaisingEvents be used on a process that is already running at the time my application starts?

Currently I have a program that starts another application and monitors that application to keep it running using this code:

System.Diagnostics.Process startProgram =
    System.Diagnostics.Process.Start("program.exe", String.Format(Program.ConnectionArg));
startProgram.EnableRaisingEvents = true;
startProgram.SynchronizingObject = this;
startProgram.Exited += this.PrematureClose;

However my concern is what happens if my program is somehow killed. Is it possible to use the EnableRaisingEvents and startProgram.Exited when my program restarts?

I have a feeling I might need to ditch my code in favor of some sort of timer loop that checks if the process is still running.

EDIT 08-10-2016:

So I have tried the following code and VS based on Process Monitoring

What it's telling me:

cannot implicitly convert type 'System.Diagnostics.Process[]' to 'System.Diagnostics.Process'

System.Diagnostics.Process program_open_check = 
    System.Diagnostics.Process.GetProcessesByName("program");
program_open_check.EnableRaisingEvents = true;
program_open_check.SynchronizingObject = this;

Upvotes: 1

Views: 3570

Answers (1)

David Bentley
David Bentley

Reputation: 864

Actually solved this and forgot to post.

So, the big issue was the process object was getting disposed since it was being used as part of a using block. The code below is the a solid way of doing this. Alternatively you could define a function directly instead of using a delegate.

        Process[] processes_array = Process.GetProcessesByName("someprogram");
        foreach (Process some_process in processes_array)
        {
            some_process.EnableRaisingEvents = true;
            some_process.Exited += delegate (object sender, EventArgs args)
            {
                // Do work.
                // DISPOSE PROCESS IF NOT USING IT AFTER THIS!!
            };
        }

Upvotes: 1

Related Questions