Delphi Multi-Threading Message Loop

后端 未结 3 690
执笔经年
执笔经年 2020-12-28 10:39

My application has several threads: 1) Main Thread 2) 2 Sub-Main Threads (each with Message Loop, as shown below), used by TFQM 3) n Worker Threads (simple loop, containing

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 11:02

    1) You don't need in AllocateHwnd within your thread. First call to GetMessage will create a separate message queue for this thread. But in order to send message to the thread you should use PostThreadMessage function.

    Be aware that at the moment of calling PostThreadMessage the queue still could not be created. I usually use construction:

    while not PostThreadMessage(ThreadID, idStartMessage, 0, 0) do
      Sleep(1);
    

    to ensure that message queue created.

    2) For terminating thread loop I define my own message:

      idExitMessage = WM_USER + 777; // you are free to use your own constant here
    

    3) There is no need for separate event, because you can pass thread handle to WaitForSingleObject function. So, your code could look like:

      PostThreadMessage(ThreadID, idExitMessage, 0, 0);
      WaitForSingleObject(ThreadHandle, INFINITE);
    

    Take into consideration that ThreadID and ThreadHandle are different values.

    4) So, your ThreadProc will look like:

    procedure ThreadProcFQM; stdcall;
    var
      Msg: TMsg;
    begin
      while GetMessage(Msg, 0, 0, 0) 
        and (Msg.Message <> idExitMessage) do
      begin
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      end;
    end;
    

提交回复
热议问题