run<T, P> method

Future<T> run<T, P>(
  1. Future<T> task(
    1. P params
    ),
  2. P params, {
  3. Duration? timeout,
})

Runs a function task with parameters params in the isolate pool.

If all isolates are busy, the task is queued until a worker becomes available. Optionally, a timeout can be specified.

Returns a Future that completes with the result of the task.

Implementation

Future<T> run<T, P>(Future<T> Function(P params) task, P params,
    {Duration? timeout}) async {
  await init(); // Ensure pool is ready

  final completer = Completer<T>();
  final taskReq = _TaskRequest(task, params, completer, timeout);

  // Assign to idle worker if available
  final idleWorker = _workers.firstWhereOrNull((w) => w.idle);
  if (idleWorker != null) {
    idleWorker.runTask(taskReq);
  } else {
    // Otherwise queue the task
    _taskQueue.add(taskReq);
  }

  return completer.future;
}