Search code examples
multithreadingdelphigenericsdelphi-2009

How to use generics to create a thread class that returns different values


I admit it, I am learning a lot from Stack Overflow.

After on this question I understood how to make a decoupled background Thread class that returns an integer I am now wondering how to make it more generic.

But how do I need to change this (where "integer" is hardcoded). I use a very long classname just for demonastrating purposes:

type
  TSyncMethod = Procedure(ThreadResult: integer) of Object;
  TBackgroundThreadWithIntegerResult = class(TThread)
  private
    FResult: integer;

to the generic counterpart?


Solution

  • type
      TBackgroundThreadWithGenericResult<T> = class(TThread)
      private
        FResult: T;
      public
        type
          TSyncMethod = Procedure(ThreadResult: T) of Object;
    

    Of course you can choose a more elaborate type name then T for your generic type. I have put the TSyncMethod into the class for simplicity.

    Usage would be TBackgroundThreadWithGenericResult<Integer>.Create(...).