在Win32中的Sleep()使程序无响应 [英] Sleep() in Win32 makes program unresponsive

查看:179
本文介绍了在Win32中的Sleep()使程序无响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上是标题说的。我想更新一个按钮包含每1秒的一个文本,当用户按下那个特定的按钮。我注意到,当程序没有焦点时,它工作正常,文本刷新正确,但当我悬停在程序或当我想点击它的菜单Windows通知我,程序是无响应,并问我如果我想要终止。当循环结束时,程序返回到其正常状态。还有任何我可能已经做的动作(例如移动它或关闭它),而 Sleep() -ing在循环后执行。下面是一些代码:

Basically exactly what the title says. I would like to update the text that a button contains every 1 second when the user presses that particular button. I have noted that when the program doesn't have focus it works alright and the text refreshes correctly but when I am hovering over the program or when I am trying to click on it's menu Windows inform me that the program is unresponsive and asks me if I want it terminated. When the loop finishes the program returns to its normal state. Also any action I might have done (like moving it around or closing it) while it was Sleep()-ing is executed after the loop. Here is a bit of code:

case ID_BUTTON_START:
// Code executed when pressing Start Button.
char startButtonText[30];  // Storing next loop text
 for (int i=5; i>0; i--)
    {
       sprintf(startButtonText, "Starting in ... %d", i);
       SendMessage(hwndButtonStart, WM_SETTEXT, 0, (LPARAM)(startButtonText));
       Sleep(1000);
     }

这是正常吗?

推荐答案

WndProc 不处理邮件在应用程序中是异步的,这意味着预期所有消息都被快速处理并且立即传递返回值。您不能在UI线程中 Sleep ,因为它将阻止处理其他UI事件。任何可能需要很长时间的繁重工作或同步请求/作业都应该在工作线程中执行。至少有三个可行的选项:

The WndProc does not process messages asynchronously within an application which means all messages are expected to be handled quickly and a return value delivered immediately. You must not Sleep in the UI thread since it will block other UI events from being processed. Any heavy work or synchronous requests/jobs which are likely to take a long time should be performed in worker threads. There are at least three viable options:


  1. 创建新的(工作线程)。

  2. 如果任务可能请经常使用,请使用线程池

  3. 设置并订阅计时器事件

  1. Create a new (worker thread) for the task.
  2. If the task is likely to be done often, use a thread pool instead.
  3. Set and subscribe to timer events.

这篇关于在Win32中的Sleep()使程序无响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆