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;
| Type | Description |
|---|---|
TPdfCancellationReason | Structured 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 |
EPdfOperationCancelled | Cancellation exception with the original Reason and message preserved for diagnostics |
IPdfCancellationToken | Compatibility worker-side token with IsCancelled polling, RegisterCallback, ThrowIfCancelled, and exception support |
IPdfCancellationTokenSource | Compatibility owner-side source with Token and idempotent Cancel |
IPdfCancellationRegistration | Stable callback registration with Id, IsRegistered, and thread-safe Unregister |
IPdfCancellationTokenEx | Extended token with cancellation metadata, callback counts, removable callback registration, and event-backed waiting |
IPdfCancellationTokenSourceEx | Extended owner source with atomic TryCancel, CancelWithReason, and strongly typed TokenEx |
TPdfCancellationTokenSource | Thread-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 |
PdfNoCancellationToken | Shared token that never cancels and avoids allocating a source for non-cancelable work |
| Member | Description |
|---|---|
CancellationMessage | Message supplied to CancelWithReason, empty until cancellation and empty for plain Cancel; read through GetCancellationMessage |
CancelledAtTick | Monotonic tick captured at the cancellation transition and zero before it; read through GetCancelledAtTick |
CallbackCount | Callbacks currently registered, dropping to zero when cancellation fires and clears the list; read through GetCallbackCount |
HasCallbacks | True while CallbackCount is non-zero; read through GetHasCallbacks |
RegisterCallbackManaged | Registers 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 |
WaitForCancellation | Blocks 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 |
| Type | Description |
|---|---|
TPdfFutureStatus | Result state: pfsSuccess, pfsCancelled, or pfsFailure |
TPdfFutureDispatchMode | Reply policy: pfdSynchronize posts the reply to the main thread, pfdWorkerThread invokes it on the worker, and pfdNone suppresses the reply |
TPdfFutureOptions | RunEx 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 |
| Member | Description |
|---|---|
Reset | Returns 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 |
CompleteSuccess | Records a successful run: stores AValue, sets Status to pfsSuccess, clears the error fields and CancellationReason, sets HasValue True, and stamps CompletedAtTick |
CompleteCancelled | Records 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 |
CompleteFailure | Records 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 |
IsSuccess | True exactly when Status equals pfsSuccess |
IsCancelled | True exactly when Status equals pfsCancelled |
IsFailure | True exactly when Status equals pfsFailure |
ElapsedMilliseconds | Run duration from StartedAtTick to CompletedAtTick, returning zero when the ticks are missing or reversed |
| Type | Description |
|---|---|
TPdfAsyncPriority | Four dequeue lanes papLow, papNormal, papHigh, and papCritical, with FIFO order inside each lane and papNormal as the default priority of Submit and TrySubmit |
TPdfAsyncTaskState | Task lifecycle: patsQueued, patsRunning, patsSucceeded, patsCancelled, or patsFailed |
TPdfAsyncDispatchMode | Reply dispatch through padWorkerThread, padSynchronize, or padNone to suppress the reply |
TPdfAsyncTaskWorker | Method-pointer work item that receives its task cancellation token |
TPdfAsyncTaskReply | Method-pointer completion callback receiving an immutable task result snapshot |
TPdfAsyncTaskResult | TaskId, State, Priority, QueuedAtTick, StartedAtTick, and CompletedAtTick timing, the ErrorMessage and ErrorClassName worker error pair, the CancellationReason with its CancellationMessage, and the isolated ReplyErrorMessage |
IPdfAsyncTask | Submitted-task handle with Cancel, timeout-aware WaitFor, atomic Snapshot, and the Id, State, Priority, Token, and IsCompleted properties |
TPdfAsyncExecutorStats | Atomic snapshot of capacity (WorkerCount, QueueCapacity), live load (QueuedCount, RunningCount, PeakQueuedCount), and cumulative outcomes (SubmittedCount, SucceededCount, CancelledCount, FailedCount, RejectedCount) |
EPdfAsyncQueueFull | Raised by Submit when a bounded queue cannot accept another task |
EPdfAsyncExecutorShutdown | Raised by Submit after executor shutdown starts |
TPdfAsyncExecutor | Reusable fixed worker pool with a bounded queue, four O(1) priority rings, cooperative task cancellation, statistics, and graceful shutdown |
| Member | Description |
|---|---|
IsCompleted | True once State reached a terminal value among patsSucceeded, patsCancelled, or patsFailed, and False while still patsQueued or patsRunning |
IsSuccess | True exactly when State equals patsSucceeded |
QueueDelayMilliseconds | Queue wait from QueuedAtTick to StartedAtTick, returning zero before the task starts running or when the ticks are reversed |
ElapsedMilliseconds | Run duration from StartedAtTick to CompletedAtTick, returning zero before completion or when the ticks are reversed |
| Member | Description |
|---|---|
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 |
Destroy | Performs the full graceful shutdown first, cancelling pending tasks and waiting for every worker before the priority queues and synchronization objects are freed |
Submit | Enqueues work through TrySubmit and raises EPdfAsyncExecutorShutdown or EPdfAsyncQueueFull when the task cannot be accepted |
TrySubmit | Non-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 |
WaitForIdle | Waits 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 |
GetStats | Returns a lock-consistent TPdfAsyncExecutorStats snapshot of capacity, live load, and cumulative outcomes |
Shutdown | Stops 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 |
WorkerCount | Fixed number of worker threads chosen at construction |
QueueCapacity | Configured queue bound, where zero means unbounded |
IsShutdown | True once Shutdown has begun, after which Submit raises and TrySubmit rejects |
| Function | Description |
|---|---|
PdfAsyncTick | Returns the monotonic millisecond tick used by future and executor metadata |
PdfAsyncTickDelta | Computes a defensive elapsed-millisecond value and returns zero for missing or reversed ticks |
PdfNextAsyncId | Returns a process-local positive ID shared by futures, callback registrations, and executor tasks |
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;
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;
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
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