0


Based on this answer I can sync my functions with main thread. And thanks to this answer I can pass parameters too. But the problem is I must declare multiple class for various procedures because parameters are different (count or type).

Q: Can I use anonymous function with TIdSync (or any other solution) so there is no need to define multiple class for various procedures?

Community
  • 1
  • 1
SAMPro
  • 1,068
  • 1
  • 15
  • 39

1 Answers1

2

TIdSync and TIdNotify do not support anonymous procedures/functions, as it would be redundant because TThread.Synchronize() and TThread.Queue() themselves support anonymous procedures (and they have static overloads that do not require a TThread object, when you are working with non-RTL threads). For example:

procedure TMyThread.Execute;
begin
  ...
  Synchronize(
    procedure
    begin
      SomeFunction(Param1, Param2, Param2);
    end
  ...
  Queue(
    procedure
    begin
      SomeFunction(Param1, Param2, Param2);
    end
  );
  ...
end;

// CreateThread() procedure
function MyThreadProc(pv: Pointer): DWORD; stdcall;
begin
  ...
  TThread.Synchronize(nil,
    procedure
    begin
      SomeFunction(Param1, Param2, Param2);
    end
  );
  ...
  TThread.Queue(nil,
    procedure
    begin
      SomeFunction(Param1, Param2, Param2);
    end
  );
  ...
  Result := 0;
end;

TIdSync is just a wrapper for TThread.Synchronize() and TIdNotify is just a wrapper for TThread.Queue(). They were introduced in a time when all TThread had available was the non-static non-anonymous Synchronize() method. With the introduction of static methods and anonymous procedures into TThread, it now does just about everything that TIdSync and TIdNotify were designed to do, making them less relevant (but they still work, of course).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thanks. Good information. Sorry for late reply. But `SomeFunction` do not executed as expected. Seems some packets not received by `SomeFunction` (or `SomeFunction` executed sometimes). Also `SomeFunction` worked great with TIdSync approach. Also it worked with Synchronize. I searched a bit and in this [link](http://delphi.about.com/b/2011/04/14/synchronizing-threads-and-gui-in-delphi-application.htm) in the last comment there is notice about `TThread.Queue` by Michael Schnell, but I don't understand how to take care. Thanks. – SAMPro Aug 02 '14 at 13:40
  • `TIdSync` simply calls `TThread.Synchronize()`. `TThread.Queue()` uses the same queue that `TThread.Synchronize()` uses. They both put a request in a global queue for the main thread to process at its leisure. So if `SomeFunction()` is not being called then the main thread is not processing sync requests, and that would affect `TThread`, `TIdSync`, and `TIdNotify` equally. – Remy Lebeau Aug 02 '14 at 16:46