afxbeginthread 为什么在线程中访问界面元素时就停止响应了?
我的定义,MyThreadProc 是线程函数
class CMyDlg : public CDialog
{
.........
public:
static UINT MyThreadProc( LPVOID pParam );
.........
}
这里是调用:
CWinThread* pThread = AfxBeginThread(MyThreadProc, LPVOID(this));
//等待线程结束
WaitForSingleObject(pThread-> m_hThread,INFINITE);
这是实现线程函数
UINT CMyDlg ::MyThreadProc( LPVOID pParam )
{
CMyDlg * pObject = (CMyDlg *)pParam;
pObject-> m_combo_saveformat.GetWindowText(szExt);
//当我调用上面这句时,停止响应了,不知道什么原因,
。。。。。。。。。。。。。。。
}
真是郁闷,不知道是什么原因,就是不响应,访问别的界面元素也是啊。
那位大哥能帮忙指教一下,不胜感激阿!
[解决办法]
停止响应?不跑了?停在那里?还是出错退出?
[解决办法]
应该是你的线程崩溃了吧。怎么会停止响应呢。设置断点
pObject-> m_combo_saveformat.GetWindowText(szExt);
你这样做其实也不合理的,你的是工作线程,不是UI线程。这样的话无疑就和UI产生了强烈的偶合。你可以使用线程拥有者的一个方法来取得你想要的数据。这些操作使用一个公共接口来实现。
[解决办法]
1:原因分析
nanfeng231(木木) 说得对,因为GetWindowText是通过给UI线程发WM_GETTEXT 去得到文本的,msdn解释如下:
If the target window is owned by the current process, GetWindowText causes a WM_GETTEXT message to be sent to the specified window or control. If the target window is owned by another process and has a caption, GetWindowText retrieves the window caption text. If the window does not have a caption, the return value is a null string. This behavior is by design. It allows applications to call GetWindowText without hanging if the process that owns the target window is hung. However, if the target window is hung and it belongs to the calling application, GetWindowText will hang the calling application.
而你的UI线程用WaitForSingleObject()阻塞了线程,所以当然死掉了。
2:解决问题的最好办法,楼上的同志们都说了:
这样做其实也不合理的,你的是工作线程,不是UI线程。这样的话无疑就和UI产生了强烈的偶合。你可以使用线程拥有者的一个方法来取得你想要的数据。这些操作使用一个公共接口来实现