7heViking
7heViking

Reputation: 7577

Listen for exit of another application

Is it possible to get notified when a specific Windows application(s) is terminated/closed when using C# and .Net? It could be any application, that is listen in the Windows job list.

Upvotes: 3

Views: 1941

Answers (3)

Yacoub Massad
Yacoub Massad

Reputation: 27861

You can use the WaitForExit method like this:

var process = Process.GetProcessById(process_id);

process.WaitForExit();

This will cause the executing thread to wait until the process has exited.

If you don't want to block the thread, and instead receive a notification when the process has exited, you can use the following:

public static void NotifyOnProcessExits(Process process, Action action)
{
    Task.Run(() => process.WaitForExit()).ContinueWith(t => action());
}

And use it like this:

NotifyOnProcessExits(process, () => Console.WriteLine("Process has exited"));

Please note that this solution will keep one thread-pool thread waiting for the process to exit. You might be able to find a better solution that is truly asynchronous, I am not sure though.

Upvotes: 6

d.moncada
d.moncada

Reputation: 17392

You could register the process and then get notified via an event using

ThreadPool.RegisterWaitForSingleObject

This will allow your application that is currently doing the monitoring to run as expected, without being blocked.

See here.

Upvotes: 0

DonO
DonO

Reputation: 1070

Yes using System.Diagnostics . I have written a program before that would kill double instances of an application. I don't think there are events you can wire up to monitor when a specific program has been closed but you can check periodically if the program still exists on the list of processes and trigger an even when it is not found.

   if(!Process.GetProcesses().Any(p => p.ProccessId == Id)); { //or Process Name
      //Your logic here
   }

Upvotes: 0

Related Questions