读书人

sleep函数 会中止一些其它程序运行解决

发布时间: 2012-03-04 11:13:33 作者: rapoo

sleep函数 会中止一些其它程序运行
在Delphi中调用sleep函数发现程序sleep了同时有部分windows的功能也被sleep了要到sleep完成。
比如新建一个程序
unit Unit2;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm2 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.Button1Click(Sender: TObject);
begin
sleep(20000);//20秒
//按下按钮后20秒内在windows的文件夹中双击word,Excel文档或.htm文件打不开
//要到sleep完成
end;

end.
是为什么?
双击图片,.txt 等无影响

[解决办法]
MSDN中有解释的:

You have to be careful when using Sleep and code that directly or indirectly creates windows. If a thread creates any windows, it must process messages. Message broadcasts are sent to all windows in the system. If you have a thread that uses Sleep with infinite delay, the system will deadlock. Two examples of code that indirectly creates windows are DDE and COM CoInitialize. Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than Sleep.

读书人网 >.NET

热点推荐