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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With