Delphi - event processing using end-to-end streams

I have a small client-server application where the server sends some messages to the client using named pipes. The client has two streams — the main GUI stream and one “receive stream”, which continues to receive messages sent by the server through the named pipe. Now that any message has been received, I would like to trigger a custom event — however, this event should not be processed on the calling thread, but on the main GUI thread — and I don’t know how to do it (and this is even possible).

Here is what I still have:

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;

Now I would like to be able to create an event handler as a member of the TForm1 class, for example

procedure TForm1.MessageReceived(Sender: TObject; Msg: tMyMessage);
begin
  //some code
end;

, . , , ( - .NET Control.BeginInvoke)

( .), , , - , .

+3
5

, :

tMyMessage = record
    mode: byte;
    //...some other fields...
end;

, Delphi - Windows , , .NET. , , . .

.NET , , , . Delphi , , .

Windows - (a HWND), SendMessage(), PostMessage(), , PostThreadMessage(). , , WPARAM, LPARAM). .

, Delphi, , .

, 32- , . - , , , . , , , .

, , , tMyMessage. , , , .

-. , . , , , . , .. , .

, . , . , . , , .

+2

PostMessage (asynch) SendMessage (synch) API "". - "" OmniThreadLibrary, " ( )

+2

FRecievedMessage: TMyMEssage

procedure PostRecievedMessage;
begin
   if Assigned(FOnMsgRcvd) then FOnMsgRcvd(self, FRecievedMessage);
   FRecievedMessage := nil;
end;

if (msgReceived) then begin
  //message was received and now is contained in Msg variable
  //fire OnMsgRcvdEvent and pass it the received message as parameter
  FRecievedMessage := Msg;
  Synchronize(PostRecievedMessage); 
end;

, PostMessage API.

+1

Synchronize. , .

0

Source: https://habr.com/ru/post/1761960/


All Articles