1

I am working on a UWP application and need to use TextBlock class in non-UI code. Attempting to instantiate TextBlock object produces "RPC_E_WRONG_THREAD (The application called an interface that was marshalled for a different thread)" exception. From the information I have gathered on the Internet I understand that I should execute my code in the UI thread. I used the following code:

CoreDispatcher^ dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;

dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler
                                                            [/* captured variables */]() {
    TextBlock ^text_block = ref new TextBlock();
    /* other code */
});

The problem is, I recieve the same exception the moment TextBlock instantiation is attempted. What am i doing wrong?

UPD: I've just realized that the project I'm working on is a DirectX UWP App. Does it mean that it can't access UI thread directly?

Delmond
  • 43
  • 1
  • 7

1 Answers1

2

Getting CoreWindow from CoreWindow::GetForCurrentThread() will only work when called from a UI thread which has an associated window. Instead, when you are on a background thread, you must access the UI thread differently:

Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
        CoreDispatcherPriority::Normal,
        ref new Windows::UI::Core::DispatchedHandler([this]()
{
   TextBlock ^text_block = ref new TextBlock();
   /* other code */
}));

This instead finds the CoreWindow of main view of your app and gets the its dispatcher. The advantage is that this approach doesn't use GetForCurrentThread so you can use it even from a background thread.

This becomes a problem when you have multiple views of your app open - then each view has its own UI thread, hence you must know which view is this action modifying so that you know which dispatcher you want to use. In this scenario, you can use the CoreApplication::Views collection to enumerate and access all application views.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91