c# WinUI 3 how to invoke on the main thread

Seth Isaacks 51 Reputation points
2023-11-16T04:17:53.0533333+00:00

Can someone please tell me how to invoke something on the main thread in c# for a WinUI 3 application?
I have found multiple things online and outdated information that simply does not work.

For example: https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/migrate-to-windows-app-sdk/guides/threading

Here is a took kit example that does not work either.

https://learn.microsoft.com/en-us/windows/communitytoolkit/extensions/dispatcherqueueextensions

This all started because I created a WPF application to test BLE. After I added the dll's to be able to use BLE it worked find....but when I ran the MSIX installer those DLL's prevented the app from running and I have no idea why. So I thought I would try to make a WinUI 3 application....and so far so good except I cannot figure out how to invoke on the UI thread.

Windows development | Windows App SDK
Windows for business | Windows Client for IT Pros | User experience | Other
Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 90,686 Reputation points
    2023-11-16T07:14:42.8733333+00:00

    I have found multiple things online and outdated information that simply does not work.

    What does not work ?

    TryEnqueue works, if it is needed.

    Like :

                bool isQueued = this.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, async () =>
                {
                    // some code with await...
                });
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.