Why Validating event handler cannot be used with async/await (C#)?

255 Views Asked by At

A have a simple textbox and I await a Delay Task inside a Validating handler. The Validated handler is always called, independently of whether I have e.Cancel = true or not! Note that if I omit the await call, validation occurs as expected. Why does this happen?

private async void textBox1_Validating(object sender, CancelEventArgs e)
{
    await Task.Delay(2000);

    e.Cancel = true;
}

private void textBox1_Validated(object sender, EventArgs e)
{
    MessageBox.Show("THIS WILL ALWAYS BE CALLED!");
}
1

There are 1 best solutions below

5
Servy On BEST ANSWER

The code that triggers the event is going to check the value of e.Cancel as soon as the event has finished calling all of the event handlers. Since your code ends up returning from the event handler and then changing the value of e.Cancel at a much later point in time, the code that fired the event handler has already long since finished checking e.Cancel and determined whether or not the validation was successful by the time you're changing the value.