简体   繁体   中英

What happens when the user closes a form performing an async task in an async event handler?

I'm writing an async event handler for a windows form but I'm not experienced with the way C# handles certain scenarios, as closing the form during a async processing triggered by an async event handler in this case.

Closing the form in question does not terminate the whole program, as the form was initialized by another form (the "main" form).

That's what the code I'm writing looks like:

private void async btn_ButtonClick(...){
   aLabel.Text = "Validating something ...";
   var isValid = await IsSomethingValid(...);
   if (isValid)
       aLabel.Text = "It's valid";

   else{
       aLabel.Text = "Sending email ...";
       await SendEmail(...);
       aLabel.Text = "Email sent";
   }
}

I've done some tests and even placing a long Thread.Sleep in SendEmail (before when it actually sends the email) and closing the form during that sleep the email ends up being sent.

Why is it so?

Would an async query also be executed even after closing its parent process?

When an async method such as your event handler hits an await , it will return to the caller. Once the awaitable method ( IsSomethingValid or SendEmail ) has returned, the remainder of the async method ( btn_ButtonClick ) will be executed.

The fact that you close the form before the awaitable method ( IsSomethingValid or SendEmail ) has returned doesn't stop the remainder of the async method ( btn_ButtonClick ) from being executed.

If you don't want to do anything after the form has been closed, you could use a flag that keeps track of whether it has been closed, eg:

public Form1()
{
    InitializeComponent();
    FormClosed += Form1_FormClosed;
}

private async void btn_ButtonClick(object sender, EventArgs e)
{
    var isValid = await IsSomethingValid();
    if (isValid && !_isClosed) //<--
    {
        MessageBox.Show("!");
    }
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e) => _isClosed = true;

private async Task<bool> IsSomethingValid()
{
    await Task.Delay(5000);
    return true;
}

Would an async query also be executed even after closing its parent process?

No, or at least not the continuation. If you send an email and exit the application, this doesn't necessarily stop the email from being sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM