在下面的简化代码中,我希望在获取结果时文本框显示“请稍候..”。然而它永远不会出现,而是文本框只显示结果functionThatTakesASecondOrTwoToRun()
xaml...
<Button Name="readDutButton" Content="Read DUT" Click="readDutButton_Click"/>
<TextBox Name="resultTextBox"/>
后面的代码....
private void readDutButton_Click(object sender, RoutedEventArgs e)
{
resultTextBox.Text = "Please wait..."; # this never appears
result = functionThatTakesASecondOrTwoToRun();
resultTextBox.Text = result;
}
这项工作需要在后台线程中进行,例如
resultTextBox.Text = "Please wait..."; // this never appears
Task.Factory.StartNew(() => functionThatTakesASecondOrTwoToRun())
.ContinueWith((t) => resultTextBox.Text = t.Result,
TaskScheduler.FromCurrentSynchronizationContext());
由于 UI 阻塞了线程,因此 UI 未获得要更新的更改。 TaskScheduler.FromCurrentSynchronizationContext() 因此ContinueWith 在UI 线程上执行并可以访问控件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)