0

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 Answers1

4

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • You may want to add that if you set `e.Cancel` to true before `await`ing anything, then it will be set when the caller checks the value since the code will run synchronously until any `await`s. – clcto Jul 11 '17 at 14:37
  • @clcto, why don't you post this finding as an answer? Setting `e.Cancel` before `await` indeed will solve the issue, as `Validated` will not be called. – Sinatr Jul 11 '17 at 14:40
  • 3
    @Sinatr It's not going to solve the problem, as presumably the asynchronous operation (in the real code) is determining if the item is valid. If the asynchronous operation *isn't* used in determining if the control is valid then it could just be omitted entirely, which as the OP mentions themselves, solves the problem. – Servy Jul 11 '17 at 14:41
  • In fact, I want to await a Task, the result of which will define if the e.Cancel should be set to true or false. This is why I do not set e.Cancel before the await call. – Pavlos Fragkiadoulakis Jul 11 '17 at 14:43
  • @Servy yes you are right. I was thinking more for other events such as closing, where you can cancel, await, and then call close if necessary: https://stackoverflow.com/questions/16656523/awaiting-asynchronous-function-inside-formclosing-event – clcto Jul 11 '17 at 14:53