MsgWaitForMultipleObjects函数用法

LongHai 2003-01-08 11:48:28
你好欢迎你!
 我用写程序时想执行一个函数,但是这个函数有可能会使整个程序死悼,所以我想在执行这个函数这前创建一个线程,它主要是用MsgWaitForMultipleObjects函数等待主线程的消息,当主线程在运行完那个进程时就发一条消息给子线程,如果主线程一直没有发消息过来时等时间一到WINDOWS就触发一条WAITE_TIMEOUT消息,这时我可以把提示报错,然后退出整个程序。但我不知怎么做,以下有一断程序就是那个原理但不知怎么不行,没有达到我要效果,不知哪位帮忙一下,谢谢!

Type
TProInfo=^ProInfo;{用来传递参数}
ProInfo=Record
Handle:THandle;
ThreadID:DWORD;
End;

Var
hThread:THandle;
ThreadID:DWORD;
PP:TProInfo;

{子线程,通过这个子线程来查看主线程的执行情况}
Procedure FrmProcess(Handle:Pointer);Stdcall;
Begin
MessageBox(TProInfo(Handle)^.Handle,'Waite_Start','Hello',MB_OK);
Case MsgWaitForMultipleObjects(1, TProInfo(Handle)^.Handle, False, 3000, QS_ALLEVENTS) of
WAIT_OBJECT_0:
Begin
MessageBox(TProInfo(Handle)^.Handle,'WAIT_OK','Hello',MB_OK);
Exit;
End;
WAIT_TIMEOUT:
MessageBox(TProInfo(Handle)^.Handle,'WAIT_TIMEOUT','Hello',MB_OK); //时间一到时弹出提示。
End;

End;

procedure TForm1.Button1Click(Sender: TObject);
begin
New(PP);
PP.Handle :=Application.Handle;
hthread:=CreateThread(nil,0,@FrmProcess,PP,0,ThreadID);
Send; 这个过程有可以使整个程序死悼
发送消息给 hthread;
end;

希望哪位知道怎么做,谢谢!(如果分数不够还可以加)
...全文
237 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
outer2000 2003-07-01
  • 打赏
  • 举报
回复
send会使主进程死掉,POST来看看如何;
g_feng 2003-07-01
  • 打赏
  • 举报
回复
即然send会使主进程死掉,不能把send放到线程中做吗?
TechnoFantasy 2003-01-08
  • 打赏
  • 举报
回复
我建议使用TThread类而不是自己创建的线程:

function TThread.WaitFor: LongWord;
var Msg: TMsg;
begin
if GetCurrentThreadID = MainThreadID then
while MsgWaitForMultipleObjects(1, FHandle, False,
INFINITE, QS_SENDMESSAGE) = WAIT_OBJECT_0 + 1
do PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE)
else
WaitForSingleObject(FHandle, INFINITE);
GetExitCodeThread(FHandle, Result);
end;
destructor TThread.Destroy;
begin
if not FFinished and not Suspended then
begin
Terminate;
WaitFor; // Be very careful
end;
if FHandle <> 0 then CloseHandle(FHandle);
inherited Destroy;
RemoveThread;
end;

TechnoFantasy 2003-01-08
  • 打赏
  • 举报
回复
我建议使用TThread类而不是自己创建的线程:

function TThread.WaitFor: LongWord;
var Msg: TMsg;
begin
if GetCurrentThreadID = MainThreadID then
while MsgWaitForMultipleObjects(1, FHandle, False,
INFINITE, QS_SENDMESSAGE) = WAIT_OBJECT_0 + 1
do PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE)
else
WaitForSingleObject(FHandle, INFINITE);
GetExitCodeThread(FHandle, Result);
end;
destructor TThread.Destroy;
begin
if not FFinished and not Suspended then
begin
Terminate;
WaitFor; // Be very careful
end;
if FHandle <> 0 then CloseHandle(FHandle);
inherited Destroy;
RemoveThread;
end;

1,184

社区成员

发帖
与我相关
我的任务
社区描述
Delphi Windows SDK/API
社区管理员
  • Windows SDK/API社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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