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
Why Is Multiple Inheritance Not Allowed in Java or C#
Capture the Screen into a Bitmap
Why Doesn't .Net/C# Optimize for Tail-Call Recursion
Casting Interfaces for Deserialization in JSON.Net
Checking for Directory and File Write Permissions in .Net
How to Change a Private Readonly Field in C# Using Reflection
Run Async Method Regularly with Specified Interval
Resolving Instances with ASP.NET Core Di from Within Configureservices
How to Create a Simple Proxy in C#
Detect Windows Version in .Net
How to Get Object Size in Memory
Recommended Servicestack API Structure
Error: "Cannot Modify the Return Value" C#
How Does the C# Compiler Detect Com Types
C# Equivalent of SQL Server Datatypes
C#: Difference Between ' += Anevent' and ' += New Eventhandler(Anevent)'