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

查看:158
本文介绍了如何在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.

方法1:使用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();
    };

方法2:使用Task.Delay

Method 2: use Task.Delay

tbkLabel.Text = "two seconds delay";

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

方法3:.NET 4.5方法,使用异步/等待

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天全站免登陆