我一直在某处读到,将 MFC ui 控件作为句柄传递给线程比将指针传递给控件更安全。
选项 1 - 传递指向静态文本的指针:
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;
}
选项 2 - 传递句柄:
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;
}
当通过多个线程访问控件时,我真的应该更喜欢使用句柄吗?或者在访问控件时依靠 SendMessage() 来解决线程安全问题就足够了吗?