When attempting to introduce a delay before executing an operation in WPF, it's important to avoid using Thread.Sleep, as this approach blocks the UI thread and can lead to unresponsive user interfaces. Instead, consider leveraging asynchronous programming techniques.
One option is to employ a DispatcherTimer. This timer runs on the UI thread and calls its Tick event handler after a specified interval:
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(); };
Another approach involves using Task.Delay:
tbkLabel.Text = "two seconds delay"; Task.Delay(2000).ContinueWith(_ => { var page = new Page2(); page.Show(); });
Here, the program creates a task that completes after a 2-second delay and then invokes the continuation delegate to show the new page.
Finally, for projects targeting .NET 4.5 or higher, the async/await pattern provides a concise and convenient way to handle delays:
public async void TheEnclosingMethod() { tbkLabel.Text = "two seconds delay"; await Task.Delay(2000); var page = new Page2(); page.Show(); }
By leveraging asynchronous techniques, developers can introduce delays into WPF operations without compromising UI responsiveness.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3