BeranekCZ BeranekCZ - 2 months ago 35
C# Question

await Task.Delay() doesnt work. Dialog close immediately


Hi. I have winforms app. In the app I have input form. A would like to simulate delay after click OK button. But code is running and form is close immediately after click. Pls help.

Button has set DialogResult to OK. I use ShowDialog to display form.

//btn click handler
private async void btnOk_Click(object sender, EventArgs e)
{
customer.UserName = "testing";
await Task.Delay(30000);
//await Task.Run(()=> System.Threading.Thread.Sleep(30000)); //I tried this too
return;
}

Answer

Your dialog closes once the btnOK_Click method returns since the button has its DialogResult property set.

And the btnOK_Click method returns as soon as Task.Delay started the delay because it's an async method. At which point the dialog closes and it appears as if the Task.Delay didn't work.

To stop that from happening you could remove the DialogResult property from the button and set the parent form's DialogResult to OK after the await statement and then manually call the Close method.

private async void btnOk_Click(object sender, EventArgs e)
{
    customer.UserName = "testing";
    await Task.Delay(30000);

    DialogResult = DialogResult.OK;
    Close();
}