Update UI async?

前端 未结 3 588
故里飘歌
故里飘歌 2021-01-13 19:28

Consider this example:

Private Sub Button_Click(
    sender As Button, e As RoutedEventArgs) Handles btn.Click

  sender.IsEnabled = False

  Thread.Sleep(50         


        
3条回答
  •  孤城傲影
    2021-01-13 20:01

    The button click event is handled by the UI thread, hence when you invoke thread.sleep you make the UI thread sleep, and you see no changes until the method ends.

    Therefore you need to run the process on a new thread, and when the process ends, make the UI changes using the dispatcher.

    For example:

    Private event TaskEnded()
    Private Sub Button_Click(sender As Button, e As RoutedEventArgs) Handles btn.Click
      btn.IsEnabled = False
      dim l as new Thread(sub()
                           Thread.Sleep(5000)
                           RaiseEvent TaskEnded
                           End Sub)
      l.start()
    End Sub
    
    Private Sub bla() Handles Me.TaskEnded
      dispatcher.BeginInvoke(sub()
                               btn.IsEnabled = True
                             end sub)
    End Sub
    

    The MVVM way you'll bind your button IsEnabled property to a boolean property in your viewModel, and update the VM propety instead on the button directly.

提交回复
热议问题