Async-await seems to use the UI thread

后端 未结 1 1379
长发绾君心
长发绾君心 2020-12-29 16:57

In a view-model I use a factory:

private async Task InitializeAsync()
{
    await InstancesAsync();
    await ProjectsAsync();
    await Admi         


        
相关标签:
1条回答
  • 2020-12-29 17:07

    I find it most useful to treat the ViewModel as having UI thread affinity. Think of it as the logical UI, even if it's not the actual UI. So all property and observable collection updates on ViewModel classes should be done on the UI thread.

    In your async methods, if you don't need to return to the UI thread, then you can use ConfigureAwait(false) to avoid resuming on the UI thread. For example, if your various initialization methods are independent, you could do something like this:

    private async Task<BaseData> InitializeAsync()
    {
      // Start all methods on the UI thread.
      var instancesTask = InstancesAsync();
      var projectsTask = ProjectsAsync();
      var adminTask = AdminAsync();
    
      // Await for them all to complete, and resume this method on a background thread.
      await Task.WhenAll(instancesTask, projectsTask, adminTask).ConfigureAwait(false);
    
      return this;
    }
    

    Also, any time you have return await, take another look to see if you can just avoid async/await entirely:

    public static Task<BaseData> CreateAsync()
    {
      var ret = new BaseData();
      return ret.InitializeAsync();
    }
    

    Finally, you should strongly avoid Dispatcher. Your Loaded event could be simplified to this:

    Loaded += async ()
    {
      DataContext = await BasisGegevens.CreateAsync();
    };
    
    0 讨论(0)
提交回复
热议问题