3

In my application the user can start a visual studio code process by clicking a button (its getting disabled after clicking). Now I want to detect, when its getting closed by the Exited-event. Before starting the process I have to check if there is already an instance running because then I have to subscribe the running process to the Exited-event (if I subscribe my new process to it, it will be triggered instantly).

The problem is, if you start one instance of VS code there are 5 'subprocesses', so I have to detect if they are all closed before I can enable the button again. After the Exited-event not all processes are finished instantly.

One solution was Thread.Sleep(500) but its not a good way to solve it in my opinion.

Is there another solution?

EDIT: The main task is to detect if the process is on its way to shut down.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

1 Answers1

0

you could create with timer or task (for example): Process.GetProcesses() and test every second if a process.id exists again, you just create the list of id to test with the known ids

        var pidlist = new List<int>() { 8, 3, 6300 };
        Process[] processes = Process.GetProcesses();
        var result = processes.Select(x => x.Id).Any(pid =>
        {
            if (pidlist.Contains(pid)) return true;
            return false;
        }) ;

you could just do a while loop with the test of var result and wait result is false.

        var pidlist = new List<int>() { 8, 2952, 630 };
        bool result = true;
        while (result)
        {
            Process[] processes = Process.GetProcesses();
            result = processes.Select(x => x.Id).Any(pid =>
            {
                if (pidlist.Contains(pid)) return true;
                return false;
            });
            System.Threading.Thread.Sleep(1000);
        }

you could simplify the calcul of result if you want

result = processes.Select(x => x.Id).Any(pid => pidlist.Contains(pid));
Frenchy
  • 16,386
  • 3
  • 16
  • 39