ComponentsScope::dispose

Scope::dispose ​

(PHP 8.6+, True Async 1.0)

php
public function dispose(): void

Closes the scope and cancels all coroutines in it. After calling dispose(), the scope is marked as both closed and cancelled. New coroutines cannot be added to a closed scope.

For a scope without the dispose-safely flag (new Scope() by default) this is equivalent to calling cancel() followed by closing the scope. A scope that carries the flag, set by allowZombies() or inherited from a parent that has it, such as the main scope, leaves its coroutines running as zombies instead, exactly like disposeSafely().

Return Value ​

No value is returned.

Examples ​

Example #1 Forcefully closing a scope ​

php
<?php

use Async\Scope;

$scope = new Scope();

$scope->spawn(function() {
    try {
        \Async\delay(60_000);
    } catch (\Async\AsyncCancellation) {
        echo "Coroutine cancelled on dispose\n";
    }
});

// All coroutines will be cancelled, scope closed
$scope->dispose();

var_dump($scope->isClosed());    // bool(true)
var_dump($scope->isCancelled()); // bool(true)

Example #2 Cleanup in a try/finally block ​

php
<?php

use Async\Scope;

$scope = new Scope();

try {
    $scope->spawn(function() {
        // Business logic
        \Async\delay(5000);
    });

    $scope->awaitCompletion(Async\timeout(5000));
} finally {
    $scope->dispose();
}

See Also ​