How to Delay an Operation Asynchronously in WPF
When attempting to create a delay in an operation, using Thread.Sleep can lead to the UI thread being blocked. To overcome this, asynchronous means should be employed.
One approach is to utilize a DispatcherTimer:
<code class="csharp">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(); };</code>
Another option involves using Task.Delay:
<code class="csharp">tbkLabel.Text = "two seconds delay"; Task.Delay(2000).ContinueWith(_ => { var page = new Page2(); page.Show(); });</code>
For .NET 4.5 and later, async/await can be employed:
<code class="csharp">// Add 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(); }</code>
By implementing asynchronous methods, the UI thread remains responsive during the delay period, allowing for seamless transitions between windows.
The above is the detailed content of How to Delay an Operation Asynchronously in WPF without Blocking the UI Thread?. For more information, please follow other related articles on the PHP Chinese website!