Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise event in C# when another process exits

I don't know if this question was already asked, but I could not find anything on it, so please lead me in the right direction if you can find something.

Basically, I would like to add an event to my current C# program to be raised when another specified process ("example.exe") exits. Is that possible?

If that is not possible, is there, instead, a way to raise an event when a specified process by direct path ("C:\somefolderpaths...\example.exe") exits?

To add: My program does NOT start the process example.exe.

like image 731
philkark Avatar asked Dec 03 '12 14:12

philkark


2 Answers

If you are using C# 4.0 you can do something like:

 Task.Factory.StartNew(() => 
  { 
      var process = Process.Start("process.exe");
      process.WaitForExit();
  }).ContinueWith(

      //THE CODE THAT WILL RUN AFTER PROCESS EXITED.  

  ); 

EDIT

If you are not creator of a process, you can use Process.GetProcessesByName function to retrive the process from already available ones.

var process = Process.GetProcessesByName("process.exe");

In this way you can avoid blocking your main thread, and run the code you need at the moment external process exited. Meanwhile, continue do something more important.

like image 107
Tigran Avatar answered Sep 22 '22 13:09

Tigran


You can use the Exited event even when you're not the owner of the process . This code works just fine:

var proc = Process.GetProcessesByName("notepad")[0];

proc.EnableRaisingEvents = true;
proc.Exited += (s, e) => { Console.Write("Done"); };

EnableRaisingEvents happens on the .NET side and has nothing to do with the creation of the process - it has all to do with waiting for the process handle to be signalled. You can do this with any wait handle (and processes are also wait handles), for example like this:

var registration 
 = ThreadPool.RegisterWaitForSingleObject(waitHandle, callbackMethod, null, -1, true);

The only time you're actually using a separate thread (from the thread pool) is while executing the callback. No need to waste a thread doing nothing while you wait.

Of course, if you want to wait as part of a synchronous process, you can still just call WaitForExit, preferrably with a timeout. Or you could just create a simple wrapper around the RegisteredWaitHandle and await.

like image 36
Luaan Avatar answered Sep 22 '22 13:09

Luaan