You need to create a VM in a separate thread. I tried two options:

  1. This option inhibits the main thread.

    public class MainVm : VmBase { public ButtonsVm ButtonsVm { get; private set; } public MainVm() { Init(); } private async void Init() { var uiContext = TaskScheduler.FromCurrentSynchronizationContext(); ButtonsVm = await Task.Factory.StartNew(() => new ButtonsVm(), CancellationToken.None, TaskCreationOptions.None, uiContext); } } 
  2. With this flies exception

      public class MainVm : VmBase { public ButtonsVm ButtonsVm { get; private set; } public MainVm() { Init(); } private async void Init() { await Task.Run(() => ButtonsVm = new ButtonsVm()); } } 

Additional information: Must create Dependency Source on the Thread as the DependencyObject.

UPDATE: ButtonsVm contains about 15 VMs in itself, and refers to the model that works with Entity, so I want to bring its creation to a separate thread so that the first connection to the database does not slow down the program.

    1 answer 1

    You must create a VM in the main thread. But model objects should be created asynchronously, in a separate thread. And work with them should also be asynchronous.

    Your problem is not at this level.

    • VladD , I see you are an experienced person in WPF , could you suggest a good example of implementing a service for creating child and dialog windows in the context of the MVVM pattern? PS I can create a separate question for this case) - sp7
    • @ sp7: Somewhere there was a question on this topic, now I will look ... - VladD
    • @ sp7: Here for modeless windows: ru.stackoverflow.com/q/455715/10105 (but there the VM binding to the window is done manually). - VladD
    • VladD , I wanted something like myWindowsSrv.ShowWindow(childVM); those. called the window creation service, gave it a VM and a service based on that VM displayed the desired View . - sp7
    • @ sp7: Well this is classic Dependency Injection :) Write a question, yes. - VladD