winui-3winuiwindows-community-toolkitwindows-app-sdk

How can I update the main thread SYNCHRONOUSLY from a background thread with Windows App SDK, C#


I have a background process that performs updates on objects that affect the UI and would like to perform these updates Synchronously from the background thread.

There seems to be no way to call something like the following:

// Called from inside Task.Run(()=>{}); or similar
private void BackgroundTask() {

   // Do work...

   // Update ObservableCollection on UI Thread
   DispatchQueue.main.sync { // like Swift
      collection.Add(...)
   }

   // Query the same ObservableCollection
   var count = collection.Length

   // etc...

}

The problem is that using this.DispatcherQueue.TryEnqueue(...) is asynchronous and there appears to be no way to await that completion on the background thread unless I missed something.

Is this possible at all and if not why not?


Solution

  • You can use the EnqueueAsync() extension from the Windows Community Toolkit.

    await DispatcherQueue.EnqueueAsync(async () =>
    {
        collection.Add(...)
    });