Using Delphi TFuture<T> for Async Operations
1. What is TFuture<T>?
Delphi provides TFuture<T> to perform asynchronous computations. It allows your
application to execute code in the background, returning a result at some future time
while keeping the main thread responsive.
TFuture<T> is part of the System.Threading unit and implements the IFuture<T> interface.
Basic pattern:
- Use TTask.Future<T> to execute a function asynchronously.
- Use .Value to retrieve the result (blocks if not ready).
- Optionally use OnTerminated or Event to get notified.
Example Use Case:
Assume a long computation to calculate a large Fibonacci number that we don't want to
block the UI.
Using Delphi TFuture<T> for Async Operations
2. Real Example in Delphi
Example: Compute Fibonacci asynchronously in Delphi
uses
System.Threading, System.SysUtils;
function SlowFibonacci(N: Integer): Int64;
begin
if N <= 1 then Exit(N);
Result := SlowFibonacci(N - 1) + SlowFibonacci(N - 2);
end;
procedure UseFuture;
var
FutureResult: IFuture<Int64>;
begin
// Start the task
FutureResult := TTask.Future<Int64>(
function: Int64
begin
Result := SlowFibonacci(40); // Heavy computation
end);
// Do something else in main thread
Writeln('Calculating...');
// Wait and get the result
Writeln('Result: ', FutureResult.Value);
end;
begin
UseFuture;
end.
Tip: Avoid blocking UI with .Value; instead use a Timer or Event system to check
IsCompleted.