サーバーが名前付きパイプを使用してクライアントにメッセージを送信する小さなクライアントサーバーアプリケーションがあります。クライアントには、メインの GUI スレッドと 1 つの「受信スレッド」の 2 つのスレッドがあり、名前付きパイプを介してサーバーから送信されたメッセージを受信し続けます。なんらかのメッセージを受信するたびに、カスタム イベントを発生させたいのですが、そのイベントは呼び出し元のスレッドではなく、メインの GUI スレッドで処理する必要があります。それも可能です)。
これが私がこれまでに持っているものです:
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;
たとえば、TForm1クラスのメンバーとしてイベントハンドラーを作成できるようにしたいと思います
procedure TForm1.MessageReceived(Sender: TObject; Msg: tMyMessage);
begin
//some code
end;
これは受信スレッドではなく、メイン UI スレッドで実行されます。特に、受信スレッドがイベントを発生させ、イベント ハンドラー メソッドの戻りを待たずに実行を継続することを希望します (基本的には、.NET Control.BeginInvokeメソッドのようなものが必要です) 。
私はこれが本当に初心者なので(数時間前にカスタムイベントを定義する方法を学ぼうとしました)、それが可能かどうか、または何か間違っているかどうかはわかりません。あなたの助け。