title: Delphi - Cross-thread event handling
body: <p>I have a small client-server application, where server sends some messages to the client using named pipes. The client has two threads - main GUI thread and one "receiving thread", that keeps receiving the messages sent by server via the named pipe. Now whenever some message is received, I'd like to fire a custom event - however, that event should be handled not on the calling thread, but on the main GUI thread - and I don't know how to do it (and whether it's even possible).</p>
  
  <p>Here's what I have so far:</p>
  
  <pre><code>tMyMessage = record
      mode: byte;
      //...some other fields...
  end;
  
  TMsgRcvdEvent = procedure(Sender: TObject; Msg: tMyMessage) of object;
  
  TReceivingThread = class(TThread)
  private
    FOnMsgRcvd: TMsgRcvdEvent;
    //...some other members, not important here...
  protected
    procedure MsgRcvd(Msg: tMyMessage); dynamic;
    procedure Execute; override;
  public
    property OnMsgRcvd: TMsgRcvdEvent read FOnMsgRcvd write FOnMsgRcvd;
    //...some other methods, not important here...
  end;
  
  procedure TReceivingThread.MsgRcvd(Msg: tMyMessage);
  begin
    if Assigned(FOnMsgRcvd) then FOnMsgRcvd(self, Msg);
  end;
  
  procedure TReceivingThread.Execute;
  var Msg: tMyMessage
  begin
    //.....
    while not Terminated do begin //main thread loop
      //.....
      if (msgReceived) then begin
        //message was received and now is contained in Msg variable
        //fire OnMsgRcvdEvent and pass it the received message as parameter
        MsgRcvd(Msg); 
      end;
      //.....
    end; //end main thread loop
    //.....
  end;
  </code></pre>
  
  <p>Now I'd like to be able to create event handler as member of TForm1 class, for example </p>
  
  <pre><code>procedure TForm1.MessageReceived(Sender: TObject; Msg: tMyMessage);
  begin
    //some code
  end;
  </code></pre>
  
  <p>that wouldn't be executed in the receiving thread, but in main UI thread. I'd especially like the receiving thread to just fire the event and continue in the execution without waiting for the return of event handler method (basically I'd need something like .NET <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx" rel="nofollow noreferrer">Control.BeginInvoke</a> method)</p>
  
  <p>I'm really beginner at this (I tried to learn how to define custom events just few hours ago.), so I don't know if it's even possible or if I'm doing something wrong, so thanks a lot in advance for your help.</p>