Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an MFC control to a thread or pass an handle?

I've been reading somewhere that it is safer to pass an MFC ui control to a thread as an handle rather than to pass a pointer to the control.

Option 1 - pass a pointer to static text:

TestDialog  dlg1;
::_beginthreadex(NULL, 0, &tSetTextByPointer, &dlg1.m_StaticText, 0, NULL);
dlg1.DoModal();

UINT WINAPI tSetTextByPointer(LPVOID arg)
{
    CStatic * pStaticText = static_cast<CStatic*>(arg);
    Sleep(3000);
    pStaticText->SendMessage(WM_SETTEXT, 0, (LPARAM)L"text");

    return 0;
}

Option 2 - pass an handle :

TestDialog  dlg1;
::_beginthreadex(NULL, 0, &tSetTextByHandle, &(dlg1.m_StaticText.m_hWnd), 0, NULL);
dlg1.DoModal();

UINT WINAPI tSetTextByHandle(LPVOID arg)
{
    HWND * pTextHandle = static_cast<HWND*>(arg);
    Sleep(3000);
    ::SendMessage(*pTextHandle, WM_SETTEXT, 0, (LPARAM)L"text");

    return 0;
}

Should I really prefer using handles when accessing controls by multiple threads? Or is it enough to rely on SendMessage() to cover the thread-safety matter when accessing the control?

like image 790
StackHeapCollision Avatar asked Nov 29 '25 02:11

StackHeapCollision


1 Answers

First of all you shouldn't call UI directly from worker threads. For many good reasons.

But if you do need this then use of raw HWNDs is safer. Otherwise you should check if pStaticText->SendMessage method is thread safe.

If you are on VS2010 and above I would suggest to use this approach: http://www.terrainformatica.com/2011/01/c0x-running-code-in-gui-thread-from-worker-threads/

like image 127
c-smile Avatar answered Nov 30 '25 17:11

c-smile



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!