Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

Here is my snippet:

tbkLabel.Text = "two mins delay";
Thread.Sleep(2000);
Page2 _page2 = new Page2();
_page2.Show();

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();
                Method 1 might show the new page multiple times in case the timer ticks multiple times and the app is too slow handling the first one.
– usr
                Mar 24, 2013 at 15:12
                @usr Actually it won't.  Internally the timer is a single shot and is restarted after raising the Tick event.
– Phil
                Mar 24, 2013 at 15:18
                Also I have found this does the same: tbkLabel.Text = "two mins de  lay";             Dispatcher.Invoke(new Action(() => Thread.Sleep(2000)),DispatcherPriority.Background);             Page2 _page2 = new Page2();             _page2.Show();
– BharathNadadur
                Mar 24, 2013 at 18:56
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.