Say I have an object, in my case a TThread, and I want to check one of it's properties dynamically in a function, in this case TThread.Terminated.
Is there a clean way to pass the 'property' such that I am actually passing the getter function and can therefor check the value of that property dynamically?
More detail:
My specific issue is that I am implementing threading in Delphi for the first time. I am not a fan of the fact that the standard Delphi Threading implementation seems to be to create a custom thread class to execute the method you want to thread. I found a satisfactory solution to this annoyance, where one uses a delegate to define the method to execute and then passes the actual method into the thread object at creation, allowing better separation/encapsulation of the threading code and the method to be executed by the thread. Details below.
However the implementation of the above idea I found uses TThread.Suspend to allow early termination of the method being executed. The Delphi docs mark TThread.Suspend as deprecated, and instead suggest long running methods should check the Terminated property, in order to allow early termination when requested by the parent thread. Thus I need a way to pass a reference to TThread.Terminated to the method it is executing so that that method can implement it's own early termination.
I can't pass the property by reference using the var syntax. I can't pass the underlying FTerminated field by reference, as it is a private member of TThread. I know I can just pass a reference to the TThread object into the method, but that type of circular referencing seems like a hacky way of getting around the problem.
So, is there a 'accepted' way to dynamically pass a property, or am I stuck with my current method?
Current Code: interface
uses
Windows, Messages, Classes, Forms;
type
// Method Thread Will Execute. Acts on Data. Runs in RunningThread.
// (Reference to RunningThread is past so method can check runningthread.terminated
// to allow long running methods to terminate early when parent thread requests it)
TThreadMethod = procedure (Data: pointer; RunningThread: TThread) of object;
//A Simple Thread Which Excecutes a Method on Some Data
TSimpleThread = class(TThread)
protected
Method: TThreadMethod;
Data: pointer;
procedure Execute; override;
public
constructor Create(Method: TThreadMethod; Data: pointer; CreateSuspended: boolean); overload;
end;
implementation
// SimpleThread
constructor TSimpleThread.Create(Method: TThreadMethod;
Data: pointer;
CreateSuspended: boolean );
begin
Self.Method := Method;
Self.Data := Data;
inherited Create(CreateSuspended);
Self.FreeOnTerminate := True;
end;
procedure TSimpleThread.Execute();
begin
Self.Method(Data, Self);
end;