With this test, I update the UI from a worker thread :
(thread created with _beginthreadex, changing the Background color of myButton every 1/2 second)
At beginning
#include <winrt\Microsoft.UI.Dispatching.h>_
#include <winrt\Windows.UI.Core.h>
Global variables
HANDLE g_hThread = NULL;
HANDLE g_hEvent = NULL;
BOOL g_bContinue = TRUE;
int g_nCpt = 0;
winrt::Microsoft::UI::Xaml::Window::Closed_revoker m_closedRevoker;
Test on myButton_Click
UINT idThread;
g_hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (g_hEvent)
{
g_bContinue = TRUE;
g_hThread = (HANDLE)_beginthreadex(NULL, 0, (unsigned int (WINAPI*)(void*))ChildThreadProc, (HANDLE)this, 0, &idThread);
SetEvent(g_hEvent);
}
Thread (remove space at S leep (editor bug))
static UINT WINAPI ChildThreadProc(LPDWORD lpdwData)
{
DWORD dwWait;
while (g_bContinue)
{
dwWait = WaitForSingleObject(g_hEvent, INFINITE);
if (dwWait == WAIT_OBJECT_0)
{
if (!g_bContinue)
break;
auto pThis = (MainWindow*)(lpdwData);
bool isQueued = pThis->DispatcherQueue().TryEnqueue(
Microsoft::UI::Dispatching::DispatcherQueuePriority::Normal,
[pThis]()
{
Microsoft::UI::Xaml::Media::SolidColorBrush blueBrush{ Windows::UI::Colors::Blue() };
Microsoft::UI::Xaml::Media::SolidColorBrush redBrush{ Windows::UI::Colors::Red() };
if (g_nCpt % 2 == 0)
{
pThis->myButton().Background(blueBrush);
}
else
{
pThis->myButton().Background(redBrush);
}
g_nCpt++;
});
S leep(500);
}
}
CloseHandle(g_hEvent);
return 0;
}
In Constructor
m_closedRevoker = this->Closed(winrt::auto_revoke, [&](auto&&, auto&&)
{
g_bContinue = FALSE;
SetEvent(g_hEvent);
});