Squadron 是一個 Dart/Flutter 套件,透過隔離區與 Web Worker 池實現多執行緒,讓 CPU 負載與繁重的 I/O 操作能從主執行緒卸載。它簡化了在 Android、iOS、Web、macOS、Windows 及 Linux 等平台上的平行執行。透過在原生平台使用隔離區,在 Web 上使用 Web Worker,Squadron 提升了應用程式回應性與效能。該套件提供簡單易用的 API 來管理工作執行緒與處理任務分配。
適用情境
卸載CPU密集型計算
處理大檔案 I/O 操作
在密集任務期間提高使用者介面的響應性
正在執行背景資料處理
在不阻塞主執行緒的情況下執行長時間運行的演算法
主要特色
支援 Isolate 和 Web Worker 池
跨平台相容性
簡單的任務提交 API
自動工作管理
內建錯誤處理
執行緒安全通訊
適合對象
需要高效率後台處理的開發人員
具有複雜數據轉換的應用程式
媒體或影像處理應用
即時資料分析工具
在高負載情況下需要回應式UI的應用程式
使用建議
需要理解隔離和併發
使用大量工作進程時可能會增加記憶體使用量
Web 支援受限於瀏覽器功能
不適用於輕量級任務
需要在多執行緒之間進行仔細的狀態管理
原始 README
以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。
Squadron - Multithreading and worker pools in Dart
Offload CPU-bound and long running tasks and give your apps some air!
Works everywhere: Desktop, Server, Mobile, and Browser (JS & WASM).
Dart is single-threaded by nature. While Isolate.run() is great for one-off tasks, it creates overhead for frequent operations, and is not available on browser platforms.
Squadron provides:
🔄 Persistent Worker Pools: Keep workers alive and ready to process tasks instantly.
🌐 Seamless Web Support: Uniform API for Isolates (Native) and Web Workers (JS/Wasm).
🛡️ Type Safety: Automatic code generation ensures your thread boundaries are type-safe.
📡 Streaming: Native support for Stream return types from workers.
🏗️ Architecture
sequenceDiagram
autonumber
participant App as Main App (UI)
box rgb(40, 100, 200, 0.1) Squadron / Generated Code
participant Pool as HelloWorldWorkerPool/Worker
end
box rgb(0, 150, 0, 0.1) Background Thread
participant Service as User Service
end
App->>Pool: worker.hello('Squadron')
Pool->>Service: Assign Task (Marshaled)
activate Service
Note over Service: Executing on background Isolate/Web Worker
Service-->>Pool: Return Result (Unmarshaled)
deactivate Service
Pool-->>App: Future<String> Result
Squadron uses code generation to handle the boilerplate of thread communication. Run the following command:
dart run build_runner build
This creates HelloWorldWorker and HelloWorldWorkerPool. These classes implement the same interface as your service but proxy calls to background threads.
4. Running your Worker
In your application, instantiate the worker and use it like a normal service.
[!IMPORTANT] Always stop your workers. Failure to call worker.stop() will keep your program running indefinitely.
import'hello_world.dart';
voidmain() async {
final worker = HelloWorldWorker();
try {
// Squadron starts the worker automatically on the first callfinal message = await worker.hello('Squadron');
print(message);
} finally {
worker.stop(); // Clean up the background thread
}
}
🌍 Web Support (JS & Wasm)
Squadron is designed for a "write once, run anywhere" experience. When targeting the web, you must compile your worker entry points:
# Compile to JavaScript
dart compile js ".\src\lib\hello_world.web.g.dart" -o "..\web\workers\hello_world.web.g.dart.js"# Compile to Web Assembly
dart compile wasm ".\src\lib\hello_world.web.g.dart" -o "..\web\workers\hello_world.web.g.dart.wasm"
Squadron will automatically detect the runtime environment and choose the correct implementation.
🛠️ Advanced Concepts
Data Transfer & Marshaling
Because workers run in separate memory spaces, data must be serialized ("marshaled") to cross thread boundaries. While base types (Strings, Numbers, Lists, Maps) are handled automatically, custom objects require a SquadronMarshaler.
Exceptions thrown in a worker are caught, serialized, and re-thrown on the caller's side, preserving the stack trace and error information where possible.
Debugging background workers can be tricky. Squadron provides mechanisms to forward log messages from workers back to the main thread's debugger or console.