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;
| 類型 | 說明 |
|---|---|
TPdfCancellationReason | 結構化的終止原因:pcrNone 表示來源仍存活,pcrUser 來自擁有者發起的 Cancel 與 TryCancel,NewTimeout 期限到期時為 pcrTimeout,pcrLinked、pcrShutdown 與 pcrSuperseded 分別對應呼叫端指定的連結取消、資源拆卸與工作被取代,皆透過 CancelWithReason 傳入,而 CancelWithReason 收到 pcrNone 時會以 pcrOther 作為後備值替代 |
EPdfOperationCancelled | 取消例外,保留原始 Reason 與訊息以供診斷 |
IPdfCancellationToken | 相容的工作端權杖,支援 IsCancelled 輪詢、RegisterCallback、ThrowIfCancelled 與例外 |
IPdfCancellationTokenSource | 相容的擁有者端來源,含 Token 與等冪的 Cancel |
IPdfCancellationRegistration | 穩定的回呼註冊,含 Id、IsRegistered 與執行緒安全的 Unregister |
IPdfCancellationTokenEx | 擴充權杖,具取消中繼資料、回呼計數、可移除的回呼註冊,以及以事件為基礎的等待 |
IPdfCancellationTokenSourceEx | 擴充擁有者來源,具原子性 TryCancel、CancelWithReason 與強型別 TokenEx |
TPdfCancellationTokenSource | 執行緒安全的來源實作,透過 New、NewEx 或 NewTimeout 建立;Destroy 會釋放仍在註冊的回呼持有者以及內部事件與鎖定,但不發出取消訊號、也不執行回呼 |
PdfNoCancellationToken | 永不取消的共用權杖,避免為不可取消的工作配置來源 |
| 成員 | 說明 |
|---|---|
CancellationMessage | 提供給 CancelWithReason 的訊息,取消前為空,純 Cancel 時也為空;透過 GetCancellationMessage 讀取 |
CancelledAtTick | 取消轉換當下擷取的單調刻度,在此之前為零;透過 GetCancelledAtTick 讀取 |
CallbackCount | 目前已註冊的回呼數量,取消觸發並清空清單後歸零;透過 GetCallbackCount 讀取 |
HasCallbacks | CallbackCount 非零時為 True;透過 GetHasCallbacks 讀取 |
RegisterCallbackManaged | 註冊一次性回呼並傳回 IPdfCancellationRegistration,該註冊會讓來源保持被參考並支援 Unregister;未指派的回呼傳回 nil 註冊,而在已取消的權杖上註冊會立即叫用回呼,並傳回已註銷的控制代碼 |
WaitForCancellation | 在 manual-reset 取消事件上阻塞,直到權杖取消或逾時經過,僅在取消的情形下傳回 True,且不採用輪詢 |
| 類型 | 說明 |
|---|---|
TPdfFutureStatus | 結果狀態:pfsSuccess、pfsCancelled 或 pfsFailure |
TPdfFutureDispatchMode | 回覆政策:pfdSynchronize 將回覆遞交至主執行緒,pfdWorkerThread 在工作者上叫用,pfdNone 則抑制回覆 |
TPdfFutureOptions | RunEx 的設定,由 DispatchMode 選擇回覆政策、ThreadPriority 選擇工作者排程類別;Default 傳回 pfdSynchronize 搭配 tpNormal |
TPdfFutureResult<T> | 完成封套,含 Value 與 HasValue、Status、ErrorMessage 與 ErrorClassName 配對、CancellationReason、OperationId、StartedAtTick 與 CompletedAtTick、狀態輔助成員,以及 ElapsedMilliseconds |
TPdfFutureWorker<T> | 方法指標型工作者,接收取消權杖並傳回背景結果 |
TPdfFutureReply<T> | 方法指標型回呼,接收完成的 TPdfFutureResult<T> |
TPdfFutureThread<T> | TPdfFuture<T> 使用的編譯器支援執行緒型別;透過 Create 或支援選項的 CreateEx 建構,應用程式通常呼叫 Run 或 RunEx |
TPdfFuture<T> | 射後不理的輔助型別,透過 Run 保留原有的同步回覆行為,並透過 RunEx 加入可設定的分派 |
| 成員 | 說明 |
|---|---|
Reset | 將封套還原到執行前的狀態:儲存 AOperationId、把 Status 還原為 pfsSuccess、從目前 tick 擷取 StartedAtTick、把 CompletedAtTick 歸零、清空錯誤與取消欄位、把 Value 重設為預設值,並讓 HasValue 維持 False;TPdfFutureThread<T> 會在工作者執行前以新的 PdfNextAsyncId 套用它 |
CompleteSuccess | 記錄一次成功執行:儲存 AValue、把 Status 設為 pfsSuccess、清空錯誤欄位與 CancellationReason、把 HasValue 設為 True,並標記 CompletedAtTick |
CompleteCancelled | 記錄一次合作式取消:把 Status 設為 pfsCancelled、儲存原因與訊息、在 ErrorClassName 回報 EPdfOperationCancelled、把 Value 重設為預設值且 HasValue 為 False,並標記 CompletedAtTick;只有訊息的多載會以 pcrUser 轉呼叫完整版 |
CompleteFailure | 記錄一次失敗執行:把 Status 設為 pfsFailure、儲存 AClassName 與 AMessage、把 CancellationReason 重設為 pcrNone、把 Value 重設為預設值且 HasValue 為 False,並標記 CompletedAtTick |
IsSuccess | 恰好在 Status 等於 pfsSuccess 時為 True |
IsCancelled | 恰好在 Status 等於 pfsCancelled 時為 True |
IsFailure | 恰好在 Status 等於 pfsFailure 時為 True |
ElapsedMilliseconds | 從 StartedAtTick 到 CompletedAtTick 的執行時長,tick 缺失或順序顛倒時傳回零 |
| 類型 | 說明 |
|---|---|
TPdfAsyncPriority | 四條出列通道 papLow、papNormal、papHigh 與 papCritical,每條通道內部依 FIFO 順序,papNormal 是 Submit 與 TrySubmit 的預設優先權 |
TPdfAsyncTaskState | 工作生命週期:patsQueued、patsRunning、patsSucceeded、patsCancelled 或 patsFailed |
TPdfAsyncDispatchMode | 回覆分派方式:padWorkerThread、padSynchronize,或以 padNone 抑制回覆 |
TPdfAsyncTaskWorker | 方法指標型工作項目,接收所屬工作的取消權杖 |
TPdfAsyncTaskReply | 方法指標型完成回呼,接收不可變的工作結果快照 |
TPdfAsyncTaskResult | TaskId、State、Priority、QueuedAtTick、StartedAtTick 與 CompletedAtTick 時序、ErrorMessage 與 ErrorClassName 工作者錯誤配對、連同 CancellationMessage 的 CancellationReason,以及隔離的 ReplyErrorMessage |
IPdfAsyncTask | 已提交工作的控制代碼,含 Cancel、支援逾時的 WaitFor、原子性 Snapshot,以及 Id、State、Priority、Token 與 IsCompleted 屬性 |
TPdfAsyncExecutorStats | 原子性快照,涵蓋容量(WorkerCount、QueueCapacity)、即時負載(QueuedCount、RunningCount、PeakQueuedCount)與累計結果(SubmittedCount、SucceededCount、CancelledCount、FailedCount、RejectedCount) |
EPdfAsyncQueueFull | 當有界佇列無法再接受工作時由 Submit 引發 |
EPdfAsyncExecutorShutdown | 在執行器開始關閉後由 Submit 引發 |
TPdfAsyncExecutor | 可重複使用的固定工作者集區,具備有界佇列、四個 O(1) 優先權環、合作式工作取消、統計資訊與平滑關機 |
| 成員 | 說明 |
|---|---|
IsCompleted | State 進入 patsSucceeded、patsCancelled 或 patsFailed 等終態後為 True,仍是 patsQueued 或 patsRunning 時為 False |
IsSuccess | 恰好在 State 等於 patsSucceeded 時為 True |
QueueDelayMilliseconds | 從 QueuedAtTick 到 StartedAtTick 的佇列等待時間,工作尚未開始執行或 tick 順序顛倒時傳回零 |
ElapsedMilliseconds | 從 StartedAtTick 到 CompletedAtTick 的執行時長,尚未完成或 tick 順序顛倒時傳回零 |
| 成員 | 說明 |
|---|---|
Create(AWorkerCount: Integer; AQueueCapacity: Integer) | 啟動固定的工作者集合,非正數的數量會被調整為 1,超過 256 的數量與負數容量會被拒絕;容量為零表示佇列無上限 |
Destroy | 先執行完整的平滑關機,取消待處理工作並等待每個工作者結束,然後才釋放優先權佇列與同步物件 |
Submit | 透過 TrySubmit 將工作排入佇列,無法接受工作時引發 EPdfAsyncExecutorShutdown 或 EPdfAsyncQueueFull |
TrySubmit | 不引發例外的排入佇列版本;關機已開始或有界佇列已滿時傳回 False 並遞增 RejectedCount,成功時透過 ATask 傳回工作控制代碼,未指派的工作者會引發 EInvalidOperation |
WaitForIdle | 等待佇列與執行中的工作全部清空,期間以片段方式幫浦同步回呼,讓 padSynchronize 回覆能在呼叫端主執行緒上完成 |
GetStats | 傳回鎖定一致的 TPdfAsyncExecutorStats 快照,涵蓋容量、即時負載與累計結果 |
Shutdown | 停止接受新工作,在 ACancelPending 保持 True 時取消仍在佇列中的工作,以合作方式等待執行中的工作完成,然後終止並釋放每個工作者;並行呼叫者共享同一次關閉操作,而從同一執行器的工作、回覆或關閉回呼中呼叫會引發 EInvalidOperation |
WorkerCount | 建構時選定的固定工作者執行緒數量 |
QueueCapacity | 設定的佇列上限,零表示無上限 |
IsShutdown | Shutdown 開始後為 True,此後 Submit 會引發例外、TrySubmit 會拒絕 |
| 函式 | 說明 |
|---|---|
PdfAsyncTick | 傳回 future 與執行器中繼資料所使用的單調毫秒刻度 |
PdfAsyncTickDelta | 計算防禦性的經過毫秒數,遺失或逆轉的刻度會傳回零 |
PdfNextAsyncId | 傳回處理序本機的正整數 ID,由 future、回呼註冊與執行器工作共用 |
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 建置保留 TThreadPriority 選項值 tpIdle、tpLowest、tpLower、tpNormal、tpHigher、tpHighest 與 tpTimeCritical,維持原始碼相容性,但平台 RTL 只支援預設排程路徑。tpNormal 使用該路徑;以其他執行緒優先權建立 Future,會在啟動 Worker 前拋出 ENotSupportedException
重複或突發性的工作請使用 TPdfAsyncExecutor,讓工作重用固定的一組執行緒,而不是每個操作都建立一條執行緒
正數的佇列容量提供確定性的背壓,零則表示佇列無上限;執行中的工作不佔用佇列槽位
無效的執行器優先權、派送模式與 Future 選項列舉值,會在工作送出或執行緒啟動之前引發 EInvalidOperation
擲出 EPdfOperationCancelled 的 Worker 會把例外的原因與訊息保留在工作結果中,即使其 token 並未被單獨取消
優先權排程在通道之間是嚴格的,通道內部則為 FIFO,因此請將 papCritical 與 papHigh 保留給真正延遲敏感的工作
從主執行緒呼叫時,WaitForIdle 會處理同步回呼,讓 padSynchronize 回覆能夠完成而不發生關機死結
背景呼叫者不會處理同步回呼,因此使用 padSynchronize 時主執行緒必須持續服務它們;當另一位呼叫者加入工作者時,主執行緒上並行的關閉呼叫者會繼續服務回呼
執行器的解構不要放在它自己的工作與回呼內進行;需要應用程式層級的清理時,請在回呼返回後再提出,而回呼只想檢查執行器是否閒置時,可使用 WaitForIdle(0)
PdfAsyncTick 在 Delphi 與 FPC 上(含 POSIX 目標)都使用單調時鐘,因此改變牆鐘時間不會影響逾時或時長的計算;其絕對原點未指定
每個逾時來源在取消或到期之前都會持有一條輕量等待執行緒,因此需要建立大量短時限時,建議改用共用的應用程式計時器或期限排程器
PDFium 物件擁有權規則仍然適用:為每個並行工作者建立或隔離一個 TPdf 實體,並且不要並行修改或算繪同一個作用中文件實體
合作式取消無法中斷不回到輪詢點的原生呼叫;需要另行設定的 Windows LPAC/工作物件執行 profile,請用 FPdfNativeWorker
原有的 IPdfCancellationToken、IPdfCancellationTokenSource、TPdfCancellationTokenSource.New 與 TPdfFuture<T>.Run API 保持原始碼相容
只有當需要結構化診斷、可移除回呼、逾時等待或原子性取消擁有權時,才使用擴充介面
回呼仍使用方法指標而非匿名方法,因此相同的 API 可在 Delphi、C++Builder 與 Free Pascal 下編譯