user15896272
user15896272

Reputation:

ViewModel changes ignored in very specific scenario

I have a method tied to a button that does time consuming thing. So I have created a label and binded it to property to inform user that application is actually doing something.

private void Button_OnClick(object sender, RoutedEventArgs e)
{
   _viewModel.BottomBarMessage = "Loading..."; //part 1
   //do very long thing, for example
   System.Threading.Thread.Sleep(3000); //wait for 3 seconds to simulate long operation
   _viewModel.BottomBarMessage = "Done."; //part 2
}

Issue is part 1 does not seem to be ever executed. Label switches to Done but never to Loading. I have suspected its because UI gets blocked, but changing Sleep to be executed as Task changes nothing.

Upvotes: 0

Views: 45

Answers (1)

Leonid Malyshev
Leonid Malyshev

Reputation: 475

use await Task.Delay instead of Thread.Sleep - you are blocking UI thread. Something like:

 private async void Button_OnClick(object sender, RoutedEventArgs e)
 {
    _viewModel.BottomBarMessage = "Loading..."; //part 1
    //do very long thing, for example
    await Task.Delay(3000); 
    _viewModel.BottomBarMessage = "Done."; //part 2
 }

Upvotes: 2

Related Questions