MessageLoop within Thread

后端 未结 2 644
野的像风
野的像风 2021-02-07 21:13

How can I implement a message loop within a thread using OTL? Application.ProcessMessages; is what i used so far but it isn\'t very safe to use it.

Thanks

2条回答
  •  生来不讨喜
    2021-02-07 21:42

    This is how I pull messages off a thread's queue:

    while GetMessage(Msg, 0, 0, 0) and not Terminated do begin
      Try
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      Except
        Application.HandleException(Self);
      End;
    end;
    

    Using Application.ProcessMessages will pull messages of the queue of the calling thread. But it's not appropriate to use in a message loop because it won't block. That's why you use GetMessage. It blocks if the queue is empty. And Application.ProcessMessages also calls other TApplication methods that are not designed to be thread safe. So there are plenty of reasons not to call it from a thread other than the main thread.

    When you need to terminate the thread, then I do this:

    Terminate;
    PostThreadMessage(ThreadID, WM_NULL, 0, 0);
    //wake the thread so that it can notice that it has terminated
    

    None of this is OTL specific. This code all is intended to live in a TThread descendent. However, the ideas are transferable.


    In the comments you indicate that you want to run a busy, non-blocking message loop. You would use PeekMessage for that.

    while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
      Try
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      Except
        Application.HandleException(Self);
      End;
    end;
    

提交回复
热议问题