Is it considered bad practice for ViewModel objects to contain a dispatcher?

The WPF application is structured using the MVVM pattern. ViewModels will communicate asynchronously with the server, and when the requested data is returned, the callback in the ViewModel is launched and it will do something with this data. This will work in a thread that is not a user interface thread. Sometimes these callbacks include work that needs to be done in the UI thread, so I need a dispatcher. These can be things like:

  • Adding data to an ObservableCollection
  • Trigger Prism Commands That Will Install Something Displayed In The GUI
  • Creating WPF Objects

I try to avoid the latter, but the first two points here are reasonable for ViewModels. So; is it ok if viewmodels hold the dispatcher to be able to invoke commands for the user interface thread? Or is this considered bad practice? And why?

+5
source share
4 answers

Since the ObservableCollection must be updated in the stream to which it belongs (subject to the GUI application), and the ObservableCollections must be part of the ViewModel, then there is a clear case for the ViewModel with the Manager.

I do not see that this is part of the Model.

+3
source

a ViewModel . Windows Forms ( Windows Forms ), - ( - , ViewModel Javascript) . Dispatcher.

, , Dispatcher ViewModel . ViewModel Dispatcher:

    protected override void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (Deployment.Current.Dispatcher == null || Deployment.Current.Dispatcher.CheckAccess())
        {
            base.OnPropertyChanged(sender, e);
        }
        else
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => base.OnPropertyChanged(sender, e));
        }
    }

System.Windows, , .: →

+2

kyoryu, , logMary ServiceModel ( ), , .

Yesterday, I experimented several times with WPF, a simple virtual machine and threads, and came to the conclusion that I absolutely need to transfer the dispatcher to the virtual machine.

Also see Using WPF UI Stream Always Must Ensure STA Flat Mode, Is It?

+1
source

Use instead AsyncOperation.

0
source

All Articles