-1

I have a simple WPF app I'm trying to simulate the idea of waiting for something to load. I thought I could do a Thread.Sleep in the following snippet but it didn't sleep for 10 seconds before setting to busy indicator to false.

What concept am I missing here about WPF and how can I simulate a wait time?

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Thread.Sleep(10000);
        LogonBusyIndicator.IsBusy = false;

    }
Rod
  • 14,529
  • 31
  • 118
  • 230

1 Answers1

2

Never call Thread.Sleep in the main thread of a UI application. It will block the thread and hence the UI.

You may instead await a Task.Delay call in an async Loaded event handler:

public MainWindow()
{
    InitializeComponent();
    Loaded += MainWindow_Loaded;
}

private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    await Task.Delay(10000);
    LogonBusyIndicator.IsBusy = false;
}

Or

public MainWindow()
{
    InitializeComponent();

    Loaded += async (s, e) =>
    {
        await Task.Delay(10000);
        LogonBusyIndicator.IsBusy = false;
    };
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • I was doing the ```Thread.Sleep``` for temporary testing purposes, but apparently it didn't block it for me though. Any insight as to why? – Rod May 24 '20 at 16:55
  • No idea what exactly you've observed, but it will definitely block the current (i.e. the UI) thread. – Clemens May 24 '20 at 16:56
  • In my code above, when the WPF window first loaded, the busy indicator did not wait 10 seconds to turn off. It immediately set it to false. – Rod May 24 '20 at 16:58
  • 2
    Sure, but it would take ten seconds before you see the window at all. – Clemens May 24 '20 at 17:06
  • ahh, ok. I see (in 10 seconds) – Rod May 24 '20 at 17:07
  • What is ```Loaded```? Seems like there should have been an override or something like OnLoaded would be more intuitive. – Rod May 24 '20 at 17:09
  • 1
    Loaded is an event, and because it is, you can attach an `async void` handler method. You can't override a non-async method with an async one. – Clemens May 24 '20 at 17:13
  • Thank you for the quick help. And everyone else who answered. – Rod May 24 '20 at 17:14