-1

The following code creates an update thread that is supposed to notify the view every 10ms.

    DataVM::DataVM()
    {
        Update = UpdateLoop();
    }
    
    IAsyncAction DataVM::UpdateLoop()
    {
        co_await resume_background();
        while ( true )
        {
            std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
            RaisePropertyChanged( L"SomeProperty" );
        }
    }

The issue: Something goes wrong when RaisePropertyChanged is called and the thread stops. Inspecting the Update object it shows Status=Error after RaisePropertyChanged has been called once. Without the call it keeps running. There is also nothing wrong with my impl of RaisePropertyChanged, it works as intended in other places.

Questions:

  1. How do I go about debugging things like this? Where would I see the Error occurring?
  2. How do I correctly call RaisePropertyChanged so that my code works as intended?
  3. Other/better ways to update on a regular basis? (This one seems pretty easy, though, if only it worked)
non-user38741
  • 671
  • 5
  • 19
  • 1
    I'm pretty sure that you need to call `RaisePropertyChanged` on the UI thread. [Advanced concurrency and asynchrony with C++/WinRT](https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/concurrency-2) explains how to do that. Also make sure to read [Safely accessing the `this` pointer in a class-member coroutine](https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/weak-references#safely-accessing-the-this-pointer-in-a-class-member-coroutine). – IInspectable Jan 07 '22 at 17:19

1 Answers1

0

A simple way seems to be:

    IAsyncAction DataVM::UpdateLoop()
    {
        winrt::apartment_context ui_thread;

        while ( true )
        {
            co_await resume_background();
            co_await std::chrono::milliseconds( 10 );
            co_await ui_thread;
            RaisePropertyChanged( L"SomeProperty" );
        }

    }

where one 'captures' the UI thread and regularly passes control back. Not sure what happens when this goes out of scope, though. Might need to do something in the destructor.

non-user38741
  • 671
  • 5
  • 19