Let's imagine we have such code:
public class MyProcess
{
private Process _process;
public event EventHandler OnFinish;
public MyProcess(string pathToExe)
{
_process = new Process();
_process.StartInfo.FileName = pathToExe;
}
public int Start()
{
_process.Exited += _processExited;
_process.Start();
return _process.Id;
}
public void Stop()
{
_process.Stop();
}
private void _processExited(object sender, EventArgs e)
{
OnFinish?.Invoke();
}
}
public class MyProgram
{
private static int stoppedProcs = 0;
public static void Main(string[] args)
{
var proc = new MyProcess("foo.exe");
proc.OnFinish += proc_OnFinish;
proc.Start();
proc.Stop();
//Wait here to display 1 instead of 0
Console.WriteLine(stoppedProcs);
}
private static void proc_OnFinish(object sender, EventArgs e)
{
stoppedProcs++;
}
}
I create and launch process. Then I want to stop it and continue only after I handle the event. The problem is I do not invoke event by myself as it is done by OS. How can I understand that event handlers are finished?