全部,我想更新 ToolStripMenu
以显示 SqlConnection
失败。我希望错误消息显示一段时间 timeToWaitMs
(以毫秒为单位),然后在一段时间和一些操作后将 UI 刷新回正常状态。目前我正在做(删除了一些不必要的细节)
public void ShowErrorWithReturnTimer(string errorMessage, int timeToWaitMs = 5000)
{
// Update the UI (and images/colors etc.).
this.toolStripLabelState.Text = errorMessage;
// Wait for timeToWait and return to the default UI.
Task task = null;
task = Task.Factory.StartNew(() =>
{
task.Wait(timeToWaitMs);
});
// Update the UI returning to the valid connection.
task.ContinueWith(ant =>
{
try
{
// Connection good to go (retore valid connection update UI etc.)!
this.toolStripLabelState.Text = "Connected";
}
finally
{
RefreshDatabaseStructure();
task.Dispose();
}
}, CancellationToken.None,
TaskContinuationOptions.None,
mainUiScheduler);
}
我遇到的问题是 task.Wait(timeToWaitMs);
导致显示 Cursors.WaitCursor
- 我不想这样。如何强制错误消息显示一段时间,然后返回非错误状态?
感谢您的宝贵时间。
最佳答案
我根本不会在这里使用任务 - 至少在没有 C# 5 中的异步功能的情况下不会。在 C# 5 中你可以只写:
await Task.Delay(millisToWait);
但在您了解之前,我只会使用适合您的 UI 的计时器,例如System.Windows.Forms.Timer
或 System.Windows.Threading.DispatcherTimer
.只需将您当前获得的内容用作计时器的“滴答”处理程序的延续,并适本地安排它。
关于c# - 在继续更新 UI 之前强制任务等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13379002/