Are there any disadvantages if I use the callback function inside the thread to communicate with the main thread of my application?

I wrote the Thread.descendent class, and to associate my thread with the main thread, I use the callback function, so I wonder if this is a valid solution or should I use Windows messages instead?

type TMyCallBack= procedure(const Param1,Param2: string) of object; TMyThread= class(TThread) private P1 : string; P2 : string; MyCallBack : TMyCallBack; procedure Process; public Constructor Create(CallBack : TMyCallBack); overload; destructor Destroy; override; procedure Execute; override; end; procedure TMyThread.Process; begin FCallBack(P1,P2); end; constructor TMyThread.Create(CallBack : TMyCallBack); begin inherited Create(False); FreeOnTerminate := True; MyCallBack := CallBack; end; procedure TMyThread.Execute; begin while True and not Terminated do begin AResult:= FListener.GetResult(Param1,Param2,5000); if not VarIsNull(AResult) then begin P1:=AResult.Value1; P2:=AResult.Value2; Synchronize(Process); end; end; end; 
+4
source share
2 answers

While you are using Synchronize, you should be fine.

+1
source

If you make a callback through Synchronize , this is normal, like most Delphi implementations:

  • create a callback structure containing the callback and event descriptor
  • add callback structure to locked global list
  • post a post in the main thread to wake it from WaitMessage or similar
  • waiting for an event to complete the callback

This may or may not be better than using raw window messages, for example:

  • the callback list is checked in clearly defined places and, as such, is not much suitable for return problems.
  • for the same reasons, it is certainly a little less productive.
  • this can cause problems with modal windows and custom pop-up menus that allow you to send sent messages, but in some cases can bypass the processing of the synchronization list

As long as the callback processing should be delayed / canceled, and you can say for sure that it does nothing that could cause the processing of sent messages (as most window-related procedures do)! using SendMessage , with the appropriate parameter marshaling.

+1
source

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


All Articles