简体   繁体   中英

Setting a ViewModel UI Property from an Async Method

I am trying to set a ViewModel List property from an async method, but this ends with the following error:

{"The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"}

The error is pretty clear. What is not clear to me is the best approach to overcome this issue and successfully set the property that in turn updates the UI.

The following attempt ends with Object reference not set to an instance of an object Error at the point of Initializing the Dispatcher:

 private async Task DoSomething()
    {
        DispatcherHelper.Initialize();
        DispatcherHelper.CheckBeginInvokeOnUI(
          () =>
          {
           ViewModelProperty = SomeResult;
          });
    }

What is the best approach to solving this problem?

Update :

I ended up initializing the DispatcherHelper globally inside the App.xaml.cs OnLaunched method.

It looks like you are calling DispatcherHelper.Initialize() in a background thread. Here it doesn't have access to a Dispatcher object.

You need to initialize it on the UI thread, as stated in the documentation :

Initialize. This method should be called once on the UI thread to ensure that the UIDispatcher property is initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM