如何在 WPF 中执行操作之前设置延迟 [英] How to put delay before doing an operation in WPF

查看:90
本文介绍了如何在 WPF 中执行操作之前设置延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的片段:

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

推荐答案

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

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

方法一:使用 DispatcherTimer

Method 1: use a 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();
    };

方法二:使用Task.Delay

Method 2: use Task.Delay

tbkLabel.Text = "two seconds delay";

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

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

Method 3: The .NET 4.5 way, use 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();
}

这篇关于如何在 WPF 中执行操作之前设置延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆