Why ShowDialog-response delayed in async event handlers?

喜夏-厌秋 提交于 2020-11-29 21:36:34

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/64866056/why-showdialog-response-delayed-in-async-event-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!