【发布时间】:2011-08-25 12:10:48
【问题描述】:
从工作线程访问 MFC 控件的最佳方式是什么?
什么是访问控件的 MFC 惯用方式?
我在这里读到http://www.flounder.com/workerthreads.htm 以下方法,但我不太喜欢CString 的new,我怎么能确定CString 会正确deleted?
typedef struct tagTP
{
HWND hwnd;
int n;
} TP;
BEGIN_MESSAGE_MAP(CMyDlg, CDialog)
// ...
ON_MESSAGE( UWM_UPDATE_RESULTS, OnUpdateResults )
END_MESSAGE_MAP()
void CMyDlg::OnBnClickedDoWork()
{
TP* tp = new TP;
tp->hwnd = m_hWnd;
tp->n = 42;
AfxBeginThread( doWork, tp );
}
UINT CMyDlg::doWork(LPVOID p)
{
TP* tp = reinterpret_cast< TP* >(p);
CWnd* dlg = FromHandle( tp->hwnd );
if ( tp->n == 42 ) {
CString* s = new CString( "Is the Answer to the Ultimate Question of Life, the Universe, and Everything" );
dlg->PostMessage( UWM_UPDATE_STATUS, 0, reinterpret_cast< LPARAM >(s) );
}
return 0;
}
LRESULT CMyDlg::OnUpdateResults(WPARAM,LPARAM lParam)
{
CString* s = reinterpret_cast<CString *>(lParam);
m_result.AddString( *s );// m_result is a CListBox
delete s;
UpdateData( FALSE );
return 0;
}
【问题讨论】:
-
您应该将 CString 指针存储在 OnUpdateResults() 中的智能指针中,以确保在处理过程中出现异常时将其销毁。
标签: c++ multithreading mfc