c# - 在继续更新 UI 之前强制任务等待

标签 c# multithreading task-parallel-library wait

全部,我想更新 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.TimerSystem.Windows.Threading.DispatcherTimer .只需将您当前获得的内容用作计时器的“滴答”处理程序的延续,并适本地安排它。

关于c# - 在继续更新 UI 之前强制任务等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13379002/

相关文章:

c# - 如何在不变得丑陋的情况下使方法可取消?

c# - 在 .Net 4.0 中取消任务延迟

c# - 使 "params"成为合法的变量名

c# - 尝试在 sleep 循环中获取锁是否可以(避免死锁、饥饿等...)?

c# - 检查两个 IEnumerable 之间是否存在

c# - 是否有一个 Android 相当于 iOS 上 UISliders 的连续标志?

java - Java 中的同步 - 我们可以为 Java 中的同步访问设置优先级吗?

python - 多处理卡在 map 函数上

c# - BlockingCollection<T> 使用 TPL 数据流进行批处理

c# - RegisterWaitForSingleObject 与 System.Timers