C# 如何在 WPF 中执行操作之前设置延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15599884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:20:08  来源:igfitidea点击:

How to put delay before doing an operation in WPF

c#wpfdispatcherthread-sleep

提问by BharathNadadur

I tried to use the below code to make a 2 second delay before navigating to the next window. But the thread is invoking first and the textblock gets displayed for a microsecond and landed into the next page. I heard a dispatcher would do that.

我尝试使用以下代码在导航到下一个窗口之前延迟 2 秒。但是线程首先调用,文本块显示一微秒并进入下一页。我听说调度员会这样做。

Here is my snippet:

这是我的片段:

tbkLabel.Text = "two mins delay";
Thread.Sleep(2000);
Page2 _page2 = new Page2();
_page2.Show();

采纳答案by Phil

The call to Thread.Sleep is blocking the UI thread. You need to wait asynchronously.

对 Thread.Sleep 的调用阻塞了 UI 线程。您需要异步等待。

Method 1: use a DispatcherTimer

方法 1:使用 DispatcherTimer

tbkLabel.Text = "two seconds delay";

var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
timer.Start();
timer.Tick += (sender, args) =>
    {
        timer.Stop();
        var page = new Page2();
        page.Show();
    };

Method 2: use Task.Delay

方法二:使用Task.Delay

tbkLabel.Text = "two seconds delay";

Task.Delay(2000).ContinueWith(_ => 
   { 
     var page = new Page2();
     page.Show();
   }
);

Method 3: The .NET 4.5 way, use async/await

方法三:.NET 4.5方式,使用async/await

// we need to add the async keyword to the method signature
public async void TheEnclosingMethod()
{
    tbkLabel.Text = "two seconds delay";

    await Task.Delay(2000);
    var page = new Page2();
    page.Show();
}