Replace async / await when a C # form closes since the wait doesn't return?

I have a C # Windows Forms application that starts other processes. When the form closes, I need to close these processes and make sure that they are gone so that they do not hang, like zombie processes. My strategy is to send a shutdown command to the processes on top of the socket bridge and wait for them to finish. After 3 seconds, if they are still around, I forcibly close them (kill them).

Initially, I used the Task.Delay (3000) wait command , which resided in a form closing event. However, this did not work. By the time the application waiting for Task.Delay (3000) tried to return, the main thread had already disappeared, so the code after this statement, which forcibly closes the child processes, if they are still around, was never executed . To solve the problem, I changed the expectation of Task.Delay (3000) to a simple Thread.Sleep (3000) report . Now the code following Thread.Sleep (3000) is executed because the thread never disconnected from it.

However, it is 3 seconds when my application looks unresponsive. What technique could I use instead to make sure that the code after a 3 second wait is definitely executed without blocking the main user interface thread?

+4
source share
1 answer

In the form close event, you can start a new thread that does all this:

  • sleep for 3 seconds
  • then destroys the processes

Since sleep occurs in this separate thread, you do not need to worry about freezing the user interface. And since your thread is not a background thread, it will not disappear while it is sleeping :)

EDIT:

, . , FormClosing, , , . ?

  private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  {
     Thread t = new Thread(() =>
     {
        Thread.Sleep(10000);
        Debug.WriteLine("I am still alive!!!  So I can still kill the processes here");
        // After this point, the process shuts down, because this was the last thread running.
     });
     t.Start();

     // at this point, the form will close, but the process is still alive as long as thread `t` is alive.
  }

2:

- , : , , , . , , .

, , : , .

-4

All Articles