How to Put Delay Before Doing an Operation in Wpf

How to put delay before doing an operation in WPF

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

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();
};

Method 2: use 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

// 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();
}

Wait for some second then execute button action WPF

Alternative for tmer in windows form the DispatcherTimer control. It does pretty much the same thing, but instead of dropping it on your form, you create and use it exclusively from your Code-behind code.

The DispatcherTimer

C# WPF - Display texts using delays

(using System.Windows.Threading;)

Something like:

private void startTimer(){
Thread timerThread = new Thread(runTimer);
timerThread.Start();
}

private async void runTimer(){
await Task.Delay(2000);
Dispatcher.BeginInvoke(new Action(() => updateScreen()));
}

private void updateScreen(){
TextBox1.Text = "This is delayed";
}

WPF - Update GUI in different, static class without delay

Thread.Sleep() will block the main UI, so in your case even if the UI is already updated, you won't be able to see it.

I guess you can do MainWindow.Instance.Invalidate() before calling Thread.Sleep()



Related Topics



Leave a reply



Submit