PDFium Delphi Component Docs

FPdfAsync unit

Unit: FPdfAsync
Cancellation, future, and bounded worker-pool infrastructure for responsive PDF processing in VCL, LCL, FMX, and headless applications

Syntax

TPdfCancellationReason = (pcrNone, pcrUser, pcrTimeout, pcrLinked,
  pcrShutdown, pcrSuperseded, pcrOther);

IPdfCancellationTokenEx = interface(IPdfCancellationToken)
  function RegisterCallbackManaged(const ACallback: TThreadMethod): IPdfCancellationRegistration;
  function WaitForCancellation(ATimeoutMs: Cardinal): Boolean;
  property Reason: TPdfCancellationReason read GetReason;
  property CancellationMessage: string read GetCancellationMessage;
  property CancelledAtTick: UInt64 read GetCancelledAtTick;
  property CallbackCount: Integer read GetCallbackCount;
  property HasCallbacks: Boolean read GetHasCallbacks;
end;

IPdfCancellationTokenSourceEx = interface(IPdfCancellationTokenSource)
  function TryCancel: Boolean;
  function CancelWithReason(AReason: TPdfCancellationReason; const AMessage: string): Boolean;
  property TokenEx: IPdfCancellationTokenEx read GetTokenEx;
end;

TPdfCancellationTokenSource = class
  destructor Destroy; override;
  class function New: IPdfCancellationTokenSource; static;
  class function NewEx: IPdfCancellationTokenSourceEx; static;
  class function NewTimeout(AMilliseconds: Cardinal; const AMessage: string = ''): IPdfCancellationTokenSourceEx; static;
end;

TPdfFutureOptions = record
  DispatchMode: TPdfFutureDispatchMode;
  ThreadPriority: TThreadPriority;
  class function Default: TPdfFutureOptions; static;
end;

TPdfFuture<T> = class
  class procedure Run(const AWorker: TPdfFutureWorker<T>; const AReply: TPdfFutureReply<T>; const AToken: IPdfCancellationToken = nil); static;
  class procedure RunEx(const AWorker: TPdfFutureWorker<T>; const AReply: TPdfFutureReply<T>; const AToken: IPdfCancellationToken; const AOptions: TPdfFutureOptions); static;
end;

TPdfAsyncExecutor = class
  constructor Create(AWorkerCount: Integer; AQueueCapacity: Integer = 0);
  destructor Destroy; override;
  function Submit(const AWorker: TPdfAsyncTaskWorker; const AReply: TPdfAsyncTaskReply = nil; APriority: TPdfAsyncPriority = papNormal; ADispatchMode: TPdfAsyncDispatchMode = padWorkerThread): IPdfAsyncTask;
  function TrySubmit(const AWorker: TPdfAsyncTaskWorker; const AReply: TPdfAsyncTaskReply; out ATask: IPdfAsyncTask; APriority: TPdfAsyncPriority = papNormal; ADispatchMode: TPdfAsyncDispatchMode = padWorkerThread): Boolean;
  function WaitForIdle(ATimeoutMs: Cardinal): Boolean;
  function GetStats: TPdfAsyncExecutorStats;
  procedure Shutdown(ACancelPending: Boolean = True);
  property WorkerCount: Integer read FWorkerCount;
  property QueueCapacity: Integer read FQueueCapacity;
  property IsShutdown: Boolean read GetIsShutdown;
end;

TPdfAsyncExecutorStats = record
  WorkerCount: Integer;
  QueueCapacity: Integer;
  QueuedCount: Integer;
  RunningCount: Integer;
  PeakQueuedCount: Integer;
  SubmittedCount: Int64;
  SucceededCount: Int64;
  CancelledCount: Int64;
  FailedCount: Int64;
  RejectedCount: Int64;
end;

IPdfAsyncTask = interface
  function Cancel: Boolean;
  function WaitFor(ATimeoutMs: Cardinal): Boolean;
  function Snapshot: TPdfAsyncTaskResult;
  property Id: Int64 read GetId;
  property State: TPdfAsyncTaskState read GetState;
  property Priority: TPdfAsyncPriority read GetPriority;
  property Token: IPdfCancellationToken read GetToken;
  property IsCompleted: Boolean read GetIsCompleted;
end;

Cancellation types

TypeDescription
TPdfCancellationReasonStructured terminal reason: pcrNone while the source is live, pcrUser from owner-initiated Cancel and TryCancel, pcrTimeout when a NewTimeout deadline expires, pcrLinked, pcrShutdown, and pcrSuperseded for caller-directed linked, teardown, and replaced-work cancellation passed to CancelWithReason, and pcrOther as the fallback substituted when CancelWithReason receives pcrNone
EPdfOperationCancelledCancellation exception with the original Reason and message preserved for diagnostics
IPdfCancellationTokenCompatibility worker-side token with IsCancelled polling, RegisterCallback, ThrowIfCancelled, and exception support
IPdfCancellationTokenSourceCompatibility owner-side source with Token and idempotent Cancel
IPdfCancellationRegistrationStable callback registration with Id, IsRegistered, and thread-safe Unregister
IPdfCancellationTokenExExtended token with cancellation metadata, callback counts, removable callback registration, and event-backed waiting
IPdfCancellationTokenSourceExExtended owner source with atomic TryCancel, CancelWithReason, and strongly typed TokenEx
TPdfCancellationTokenSourceThread-safe source implementation created with New, NewEx, or NewTimeout; Destroy frees still-registered callback holders and the internal event and lock without signalling cancellation or running callbacks
PdfNoCancellationTokenShared token that never cancels and avoids allocating a source for non-cancelable work

IPdfCancellationTokenEx members

MemberDescription
CancellationMessageMessage supplied to CancelWithReason, empty until cancellation and empty for plain Cancel; read through GetCancellationMessage
CancelledAtTickMonotonic tick captured at the cancellation transition and zero before it; read through GetCancelledAtTick
CallbackCountCallbacks currently registered, dropping to zero when cancellation fires and clears the list; read through GetCallbackCount
HasCallbacksTrue while CallbackCount is non-zero; read through GetHasCallbacks
RegisterCallbackManagedRegisters a one-shot callback and returns an IPdfCancellationRegistration that keeps the source referenced and supports Unregister; an unassigned callback returns a nil registration, and registering on an already-cancelled token invokes the callback immediately and yields an already-unregistered handle
WaitForCancellationBlocks on the manual-reset cancellation event until the token is cancelled or the timeout elapses, returning True only in the cancelled case and without polling

Future types

TypeDescription
TPdfFutureStatusResult state: pfsSuccess, pfsCancelled, or pfsFailure
TPdfFutureDispatchModeReply policy: pfdSynchronize posts the reply to the main thread, pfdWorkerThread invokes it on the worker, and pfdNone suppresses the reply
TPdfFutureOptionsRunEx settings where DispatchMode selects the reply policy and ThreadPriority the worker scheduling class; Default returns pfdSynchronize together with tpNormal
TPdfFutureResult<T>Completion envelope with Value and HasValue, Status, the ErrorMessage and ErrorClassName pair, the CancellationReason, OperationId, StartedAtTick and CompletedAtTick, status helpers, and ElapsedMilliseconds
TPdfFutureWorker<T>Method-pointer worker that receives a cancellation token and returns the background result
TPdfFutureReply<T>Method-pointer callback that receives the completed TPdfFutureResult<T>
TPdfFutureThread<T>Compiler-support thread type used by TPdfFuture<T>; constructed through Create or the options-aware CreateEx, and applications normally call Run or RunEx
TPdfFuture<T>Fire-and-forget helper that preserves the original synchronized-reply behaviour through Run and adds configurable dispatch through RunEx

TPdfFutureResult<T> members

MemberDescription
ResetReturns the envelope to its pre-run state by storing AOperationId, restoring Status to pfsSuccess, capturing StartedAtTick from the current tick, zeroing CompletedAtTick, clearing the error and cancellation fields, resetting Value to its default, and leaving HasValue False; TPdfFutureThread<T> applies it with a fresh PdfNextAsyncId before the worker runs
CompleteSuccessRecords a successful run: stores AValue, sets Status to pfsSuccess, clears the error fields and CancellationReason, sets HasValue True, and stamps CompletedAtTick
CompleteCancelledRecords a cooperative cancellation: sets Status to pfsCancelled, stores the reason and message, reports EPdfOperationCancelled in ErrorClassName, resets Value to its default with HasValue False, and stamps CompletedAtTick; the message-only overload delegates to the full one with pcrUser
CompleteFailureRecords a failed run: sets Status to pfsFailure, stores AClassName and AMessage, resets CancellationReason to pcrNone, resets Value to its default with HasValue False, and stamps CompletedAtTick
IsSuccessTrue exactly when Status equals pfsSuccess
IsCancelledTrue exactly when Status equals pfsCancelled
IsFailureTrue exactly when Status equals pfsFailure
ElapsedMillisecondsRun duration from StartedAtTick to CompletedAtTick, returning zero when the ticks are missing or reversed

Executor types

TypeDescription
TPdfAsyncPriorityFour dequeue lanes papLow, papNormal, papHigh, and papCritical, with FIFO order inside each lane and papNormal as the default priority of Submit and TrySubmit
TPdfAsyncTaskStateTask lifecycle: patsQueued, patsRunning, patsSucceeded, patsCancelled, or patsFailed
TPdfAsyncDispatchModeReply dispatch through padWorkerThread, padSynchronize, or padNone to suppress the reply
TPdfAsyncTaskWorkerMethod-pointer work item that receives its task cancellation token
TPdfAsyncTaskReplyMethod-pointer completion callback receiving an immutable task result snapshot
TPdfAsyncTaskResultTaskId, State, Priority, QueuedAtTick, StartedAtTick, and CompletedAtTick timing, the ErrorMessage and ErrorClassName worker error pair, the CancellationReason with its CancellationMessage, and the isolated ReplyErrorMessage
IPdfAsyncTaskSubmitted-task handle with Cancel, timeout-aware WaitFor, atomic Snapshot, and the Id, State, Priority, Token, and IsCompleted properties
TPdfAsyncExecutorStatsAtomic snapshot of capacity (WorkerCount, QueueCapacity), live load (QueuedCount, RunningCount, PeakQueuedCount), and cumulative outcomes (SubmittedCount, SucceededCount, CancelledCount, FailedCount, RejectedCount)
EPdfAsyncQueueFullRaised by Submit when a bounded queue cannot accept another task
EPdfAsyncExecutorShutdownRaised by Submit after executor shutdown starts
TPdfAsyncExecutorReusable fixed worker pool with a bounded queue, four O(1) priority rings, cooperative task cancellation, statistics, and graceful shutdown

TPdfAsyncTaskResult members

MemberDescription
IsCompletedTrue once State reached a terminal value among patsSucceeded, patsCancelled, or patsFailed, and False while still patsQueued or patsRunning
IsSuccessTrue exactly when State equals patsSucceeded
QueueDelayMillisecondsQueue wait from QueuedAtTick to StartedAtTick, returning zero before the task starts running or when the ticks are reversed
ElapsedMillisecondsRun duration from StartedAtTick to CompletedAtTick, returning zero before completion or when the ticks are reversed

TPdfAsyncExecutor members

MemberDescription
Create(AWorkerCount: Integer; AQueueCapacity: Integer)Starts the fixed worker set, coercing a non-positive count to one and rejecting counts above 256 or negative capacities; a zero capacity keeps the queue unbounded
DestroyPerforms the full graceful shutdown first, cancelling pending tasks and waiting for every worker before the priority queues and synchronization objects are freed
SubmitEnqueues work through TrySubmit and raises EPdfAsyncExecutorShutdown or EPdfAsyncQueueFull when the task cannot be accepted
TrySubmitNon-raising enqueue that returns False, incrementing RejectedCount, when shutdown has started or the bounded queue is full; returns the task handle through ATask on success, and an unassigned worker raises EInvalidOperation
WaitForIdleWaits until nothing is queued or running, pumping synchronized callbacks in slices only on the main thread; zero performs a nonblocking poll, while a nonzero wait from the same executor's task or callback raises EInvalidOperation
GetStatsReturns a lock-consistent TPdfAsyncExecutorStats snapshot of capacity, live load, and cumulative outcomes
ShutdownStops acceptance of new work, cancels still-queued tasks when ACancelPending is left True, waits for running tasks to finish cooperatively, then terminates and frees every worker; concurrent callers share one shutdown operation, and calls from the same executor's task, reply, or shutdown callback raise EInvalidOperation
WorkerCountFixed number of worker threads chosen at construction
QueueCapacityConfigured queue bound, where zero means unbounded
IsShutdownTrue once Shutdown has begun, after which Submit raises and TrySubmit rejects

Timing and identity helpers

FunctionDescription
PdfAsyncTickReturns the monotonic millisecond tick used by future and executor metadata
PdfAsyncTickDeltaComputes a defensive elapsed-millisecond value and returns zero for missing or reversed ticks
PdfNextAsyncIdReturns a process-local positive ID shared by futures, callback registrations, and executor tasks

Cancellation example

var
  CancelSource: IPdfCancellationTokenSourceEx;
begin
  CancelSource := TPdfCancellationTokenSource.NewTimeout(5000, 'Export deadline exceeded');
  TPdfFuture<Integer>.Run(Worker, Completed, CancelSource.TokenEx);
  if UserRequestedCancel then
    CancelSource.CancelWithReason(pcrUser, 'Export cancelled by user');
end;

Bounded executor example

var
  Executor: TPdfAsyncExecutor;
  Task: IPdfAsyncTask;
begin
  Executor := TPdfAsyncExecutor.Create(4, 128);
  try
    if not Executor.TrySubmit(RenderPage, PageCompleted, Task, papHigh, padSynchronize) then
      HandleBackpressure;
    Executor.WaitForIdle(30000);
  finally
    Executor.Free;
  end;
end;

Performance and threading

Delphi POSIX builds retain the TThreadPriority option values tpIdle, tpLowest, tpLower, tpNormal, tpHigher, tpHighest, and tpTimeCritical for source compatibility, but the platform RTL supports the default scheduling path only. tpNormal uses that path; constructing a future with another thread priority raises ENotSupportedException before starting a worker

Use TPdfAsyncExecutor for repeated or bursty work so tasks reuse a fixed set of threads instead of creating one thread per operation

A positive queue capacity provides deterministic backpressure while zero keeps the queue unbounded; running tasks do not consume queue slots

Invalid executor priorities, dispatch modes, and future option enum values raise EInvalidOperation before work is submitted or a thread is started

A worker that raises EPdfOperationCancelled preserves the exception's reason and message in the task result, even when its token was not separately cancelled

Priority scheduling is strict between lanes and FIFO within a lane, so reserve papCritical and papHigh for genuinely latency-sensitive work

WaitForIdle processes synchronized callbacks when called from the main thread, allowing padSynchronize replies to finish without a shutdown deadlock

Background callers do not process synchronized callbacks, so the main thread must keep servicing them when padSynchronize is used; concurrent shutdown callers on the main thread continue servicing callbacks while another caller joins the workers

Keep executor destruction outside its own tasks and callbacks; request application-level cleanup after the callback returns, and use WaitForIdle(0) when a callback only needs to inspect whether the executor is idle

PdfAsyncTick uses a monotonic clock on Delphi and FPC, including POSIX targets, so changing the wall clock does not alter timeout or duration calculations; its absolute origin is unspecified

Each timeout source owns one lightweight waiting thread until cancellation or expiry, so a shared application timer or deadline scheduler is preferable when creating very large numbers of short-lived deadlines

PDFium object ownership rules still apply: create or isolate a TPdf instance per concurrent worker and do not mutate or render the same active document instance concurrently

Cooperative cancellation cannot interrupt a native call that does not return to a polling point; use FPdfNativeWorker for the separately configured Windows LPAC/job execution profile

Compatibility

The original IPdfCancellationToken, IPdfCancellationTokenSource, TPdfCancellationTokenSource.New, and TPdfFuture<T>.Run APIs remain source-compatible

Use the extended interfaces only when structured diagnostics, removable callbacks, timeout waiting, or atomic cancellation ownership is required

Callbacks remain method pointers rather than anonymous methods so the same API compiles with Delphi, C++Builder, and Free Pascal

See Also

TPdf.RenderPageProgressive, TPdfView.AsyncRendering