I have a C# Windows Forms app that launches other processes. When the form closes, I need to shutdown those processes and make sure they're gone so that they don't hang around as zombie processes. My strategy is that I send the processes a shutdown command over a socket bridge, and wait for them to close gracefully. After 3 seconds however, if they are still around, I force close them (kill them).
Originally I used an await Task.Delay(3000) instruction that lived in the Form's Closing event. However that didn't work. By the time the await Task.Delay(3000) statement tried to return, the main thread was already gone so the code after that statement that force closes the child processes if they're still around never executed. To solve the problem I changed await Task.Delay(3000) to a plain Thread.Sleep(3000) statement. Now the code following the Thread.Sleep(3000) executes since the thread is never switched away from as before.
However, that's 3 seconds where my app appears to be unresponsive. What technique could I use instead to make sure the code after the 3 second wait definitely executes, without blocking the main UI thread?