How to update data on UI in real-time from a thread with C++/winrt?

Clara Shi 31 Reputation points
2022-02-10T10:54:33.973+00:00

I am working on a project with WinUI 3 with C++/winrt. I need to update my UI in real-time with many data from a thread. The thread is working for receiving the data from the server. And my UI , working as a client, wants to display the data as the thread receives in real-time. I looked on the Internet and some suggested to use "Dispatcher.Invoke" to do so, like the following code:

private void Button_Click(object sender, RoutedEventArgs e)
{
Task.Run(() => Compute());
}

private void Compute()
{
// perform computation here

Dispatcher.Invoke(CoreDispatcherPriority.Normal, ShowText, this, resultString);  

}

private void ShowText(object sender, InvokedHandlerArgs e)
{
this.TextBlock.Text = (string)e.Context;
}

( URL for the code )
But it is for WPF project, I wonder how shall I do it in WinUI 3 with C++ under the namespace winrt? Or any other workaround?
I don't know if I understand it right. I am really new to it.
And because WinUI 3 is released only last year, I couldn't find any other solution for my application.
Any suggestions will be helpful to me. And an example code would be perfect!
Thanks you in advance.

Universal Windows Platform (UWP)
Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
750 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,631 questions
{count} vote

Accepted answer
  1. Castorix31 83,106 Reputation points
    2022-02-11T11:48:48.01+00:00

    With Windows App SDK/WinUI3, you must use Microsoft::UI::Dispatching::DispatcherQueue,
    as explained at : Threading functionality migration

    A simple test by changing the color of a Button in a thread inside DispatcherQueue().TryEnqueue like in the sample at Change CoreDispatcher.RunAsync to DispatcherQueue.TryEnqueue:

    173524-dispatcherqueue-tryenqueue.gif

    3 people found this answer helpful.

0 additional answers

Sort by: Most helpful