在WinForms项目中,我运行了一个算法,该算法可以不断计算数据并更新UI。它看起来像这样:
async Task BackgroundWorkAsync() {
while (true) {
var result = await Compute();
UpdateUI(result);
}
}
有时,根据result
包含的内容,我想显示MessageBox
,但立即继续运行算法。以下操作不起作用,因为它会阻止进一步的处理,直到MessageBox
被解除:
while (true) {
var result = await Compute();
UpdateUI(result);
if (...) MessageBox.Show(...); //new code
}
如何使MessageBox.Show
调用不阻塞?
(是的,这意味着可能同时弹出多个消息框。这没关系。)
一旦代码在WinForms UI线程上运行,您就可以使用Control.BeginVoke(如果此代码在Form
或Control
中)或更通用的SynchronizationContext
if (...)
BeginInvoke(new Action(() => MessageBox.Show(...)));
或
if (...)
SynchronizationContext.Current.Post(_ => MessageBox.Show(...), null);
while (true) {
var result = await Compute();
UpdateUI(result);
if (...) Task.Run(() => { MessageBox.Show(...); });
}
如果你不在乎用户在弹出窗口中按下哪个按钮,那就足够了。