【发布时间】:2015-12-10 23:28:55
【问题描述】:
我有一个在单击按钮后运行的 winform 代码:
void button1_Click(object sender, EventArgs e)
{
AAA();
}
async Task BBB( int delay)
{
await Task.Delay(TimeSpan.FromSeconds(delay));
MessageBox.Show("hello");
}
async Task AAA()
{
var task1 = BBB(1); // <--- notice delay=1;
var task2 = BBB(1); // <--- notice delay=1;
var task3 = BBB(1); // <--- notice delay=1;
await Task.WhenAll(task1, task2, task3);
}
问题:
为什么我在delay=1的时候看到一个MessageBox:
但如果我将延迟更改为:1,2,3 —
var task1 = BBB(1);
var task2 = BBB(2);
var task3 = BBB(3);
我看到了 - 3 个消息框,甚至没有点击任何消息框?
- 感谢@Noseratio 提供pointing that behaviour at first place。
【问题讨论】:
-
我的猜测是模态对话框使用了某种“嵌套消息泵”。当您一次全部推送它们时,它可能会在“外部消息泵”上批量处理整组排队的调用,从而导致一系列调用的阻塞行为。展开后,后续调用可能会在连续嵌套的消息泵中安排/处理,从而产生如您所见的一连串调用。
-
如果您不捕获 WindowsFormsSynchronizationContext
await Task.Delay(TimeSpan.FromSeconds(delay)).ConfigureAwait(false);则将显示所有消息框(延迟等于 1 时的事件)。 -
这是一个有趣的问题。您是如何发现这个问题的?
-
@Brian 来自 cmets in here
标签: c# winforms async-await