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.