0

In my .NET Framework 4.5 Windows Forms project I have an async event handler. In the event handler I open a OpenFileDialog with ShowDialog(). Then I want to do something async with the selected file. But I have some weird behavior: After closing the dialog (with Cancel or OK button) I have got a delay of 9 seconds until the ShowDialog returned with its result. While this time the application is freezed.

Here my code:

private async void buttonBrowse_Click(object sender, EventArgs e)
{
    DialogResult result = this.openFileDialog.ShowDialog(this);
    if (result != DialogResult.OK) // <- delayed more than 9 seconds after user closes dialog
        return;

    await this.LoadFileAsync(this.openFileDialog.FileName);
}

After I remove the keyword async then the code behaves as expected:

private void buttonBrowse_Click(object sender, EventArgs e)
{
    DialogResult result = this.openFileDialog.ShowDialog(this);
    if (result != DialogResult.OK) // -> no delay here
        return;

    this.LoadFileAsync(this.openFileDialog.FileName); // works, but compiler warning, because missing (await-keyword)
}

Can somebody please explain this behavior? Thanks.

Yes, I know the workaround: I could use the event handler of the dialog FileOk and move my code to this event handler. But I am curious about the documented behavior.

rittergig
  • 715
  • 1
  • 5
  • 16
  • I'm not sure someone can replicate this. If a User chooses `Cancel`, then the method returns. Otherwise, it depends on what `LoadFileAsync()` is actually doing. If it's something blocking, the calling Form freezes. The dialog is closed before that anyway. Unless you *forgot* to mention some details about the context of these operations (other Tasks / Threading involved). Or some Shell extensions you have that can get in the way. – Jimi Nov 16 '20 at 22:03
  • Could you include the `LoadFileAsync` method in the question? – Theodor Zoulias Nov 16 '20 at 23:25

1 Answers1

0

I tried a little bit. I think I was wrong. It does not depends on the async keyword.

It seems it is a Windows Forms bug. See also: Windows Forms GUI hangs when calling OpenFileDialog.ShowDialog()

If I set ShowHelp property to true. Then it works without delay. But its a different Open File Dialog (at least on latest Windows 10).

this.openFileDialog.ShowHelp = true;
rittergig
  • 715
  • 1
  • 5
  • 16