Search code examples
c++winui-3winui

How do I tell if my current thread is the UI thread in WinUI 3?


I'm working on some library code for WinUI 3 applications, and I want to assert that certain functions are called on the UI thread.

I know how to check if the current thread is the UI thread for UWP, but how do I do that for WinUI 3? CoreDispatcher and CoreWindow aren't used the same in WinUI 3.


Solution

  • Use DispatcherQueue::GetForCurrentThread instead of the CoreWindow.GetForCurrentThread().Dispatcher method for UWP. It will return a dispatcher instance if you're on the UI thread, & nullptr otherwise:

    bool IsUIThread()
    {
        return nullptr != winrt::Microsoft::UI::Dispatching::DispatcherQueue::GetForCurrentThread();
    }