0% found this document useful (0 votes)
1 views2 pages

TFuture_Async_Delphi_Example

Delphi's TFuture<T> enables asynchronous computations, allowing background code execution while keeping the main thread responsive. It is part of the System.Threading unit and can be used to perform tasks like calculating Fibonacci numbers without blocking the UI. The document provides an example of using TFuture<T> to compute Fibonacci asynchronously, emphasizing the importance of avoiding UI blocking with the .Value property.

Uploaded by

bravesaw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views2 pages

TFuture_Async_Delphi_Example

Delphi's TFuture<T> enables asynchronous computations, allowing background code execution while keeping the main thread responsive. It is part of the System.Threading unit and can be used to perform tasks like calculating Fibonacci numbers without blocking the UI. The document provides an example of using TFuture<T> to compute Fibonacci asynchronously, emphasizing the importance of avoiding UI blocking with the .Value property.

Uploaded by

bravesaw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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.

You might also like