多线程中::SendMessage()遇到的怪问题

gambolgs 2003-10-20 08:50:18
Hi!
我在编多线程程序时,遇到了用::SendMessage()把线程结束的消息发回原来的调用窗口会在release版中出violent access的错误,而在debug版中没有。我是过了改Project Settings,改成过Multithreaded DLL, multithreaded, DEBUG multithreaded, etc.还试改General为MFC DLL和MFC static,都是在同样的地方出错。出错的地方经过删加代码定位为::SendMessage()那一句。我用的cwnd.sendmessage的成员函数也出了错。我把消息处理函数改成空函数还是错,反正就是Sendmessage就要Violent access.
后来干脆把接受消息的窗口的消息处理函数改成public直接调用,居然可以用了!请问这是问什么呀?

我的线程是这样的:
UINT GenerateSliceThread(LPVOID param)
{
ThreadInfo* pInfo = (ThreadInfo*)param;
//DO SOMETHING ...

//pInfo->pvCaller->OnGenerateThreadEnded();
::PostMessage(pInfo->hwCaller, WM_GENERATE_THREAD_END, NULL, NULL); // ERROR HERE!!! BUT WHY? 已经定位为这一句出了错
//::SendMessage(), 或者CWnd.Sendmessage, CWnd.PostMessage同样错

return 829; // unreachable, in fact
}

这个ThreadInfo 的定义是这样的:
struct ThreadInfo { // this structure carries the information provided to the thread GenerateSliceThread
HWND hwCaller; // HWND of the VIEW
CNNViewBase* pvCaller; // the VIEW that requested the calculation of slice.
};
我开始线程的代码是:

ThreadInfo * info = &...;

info->hwCaller = pDemander->GetSafeHwnd();//hwCaller和pvCaller其实是同一个对象
info->pvCaller = pDemander;
this->ptGenerating = ::AfxBeginThread(GenerateSliceThread, info);

WM_GENERATE_THREAD_END 定义为WM_USER +1, 还试过改成WM_USER +100,WM_APP + 1都不行。
...全文
543 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
tyzam 2003-10-21
  • 打赏
  • 举报
回复
The SendMessage function sends the specified message to a window or windows. It calls the window procedure for the specified window and does not return until the window procedure has processed the message
The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.
你的线程要结束但是SendMessage去要等待发送的消息返回来的结果,所以就出现了错误。
flyelf 2003-10-21
  • 打赏
  • 举报
回复
消息的原型声明应该如bmon_xyz(钳工) 所说的
shinesi 2003-10-21
  • 打赏
  • 举报
回复
线程中不要用SendMessage(),用PostMessage or SendNotifyMessage
gambolgs 2003-10-21
  • 打赏
  • 举报
回复
多些各位帮助!这个问题已经解决了。

问题的根源来自于我犯的一个低级错误:我把消息处理函数声明错了!居然跟线程入口函数
UINT ThreadFunc(LPVOID *)
搞混了,声明成了一个afx_msg UINT的线程处理函数。我改成
afx_msg LRESULT HandFunc(WPARAM, LPARAM)
后就解决了。然后我又做了几次试验,试验证明我这次遇到的问题跟SendMessage无关,即使换成SendMessage也能正常运行。但是还是要感谢提出SendMessage问题的,因为这可能对其他的问题有帮助。
likevclinux 2003-10-21
  • 打赏
  • 举报
回复
在文档中心有一篇文章说,用postMessage()结束线程,可以造成violent access.
他在文章中是修改析构函数后解决的。我现在也碰到这个问题,还没解决!
gambolgs 2003-10-21
  • 打赏
  • 举报
回复
是的,我声明了afx_msg的.
而且也试过了PostMessage(),也是violent access.
bmon_xyz 2003-10-20
  • 打赏
  • 举报
回复
消息WM_GENERATE_THREAD_END的处理函数原型必须这样:
afx_msg LRESULT OnGenerateThreadEnd(WPARAM wParam, LPARAM lParam);
检查一下你是否这样声明?

15,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧