GetWindowText 卡死的一种可能的原因

最近一个项目中碰到GetWindowText经常卡死的问题,这个项目有多个线程,检查代码发现发生死锁的是一个数据线程和一个UI线程。

示意图大致如下(data thread和UI thread在同一个进程中):

无标题

1,data thread Lock();

2,data thread GetWindowText 会SendMessage(WM_GETTEXT) 给 UI window;

3,UI thread message loop , processing WM_X,在处理messagex的过程中Lock(),所以处于WM_X之后的WM_GETTEXT消息无法被相应,以致于两线程互相死锁。

所以看似是GetWindowText死锁,实际上是处理消息过程中发生死锁。

最后的解决方法是不对本进程进行GetWindowText,GetWindowText其他进程的窗口不是发送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 becoming unresponsive if the process that owns the target window is not responding. However, if the target window is not responding and it belongs to the calling application, GetWindowText will cause the calling application to become unresponsive.

To retrieve the text of a control in another process, send a WM_GETTEXT message directly instead of calling GetWindowText.

 

这个问题与通常的死锁不同,一般的死锁是在于代码逻辑上的死锁,它的死锁在于SendMessage是同步的,锁发生的原因是消息处理的先后顺序。

 

 

另外可参考:

http://zhanyonhu.blog.163.com/blog/static/16186044200810187281835/

这个链接中也差不多是相同的原因:

在窗口的Msg process函数中给本窗口SendMessage,导致当前message处理过程在等待下一个message的处理结果,结果无意外,发生死锁!

posted @   *神气*  阅读(1956)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示