0

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?

user4157124
  • 2,809
  • 13
  • 27
  • 42
usefulBee
  • 9,250
  • 10
  • 51
  • 89
  • Since you have the method marked as async, is it possible that the main thread continued on and is modifying something else at the same time and you're seeing the result of a race condition? – PhilChuang Jun 10 '17 at 03:03
  • I don't see any reason a static method like `DispatcherHelper.Initialize()` should throw `NullReferenceException`. Your question is clearly lacking some important detail. But see marked duplicate for extensive advice regarding how to diagnose and fix `NullReferenceException`. If you are unable to solve your problem using that advice, post a new question in which you provide a good [mcve] that reliably reproduces the problem, and in which you've explained in detail what you've done so far to solve the problem and what _specifically_ you are unable to figure out. – Peter Duniho Jun 10 '17 at 23:40

1 Answers1

2

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.

Julien Shepherd
  • 103
  • 2
  • 9