waitForShutdown method

Future<void> waitForShutdown([
  1. CancellationToken? token
])

Returns a Future that completes when shutdown is triggered via the given token.

Implementation

Future<void> waitForShutdown([
  CancellationToken? token,
]) async {
  var applicationLifetime =
      services.getRequiredService<HostApplicationLifetime>();

  token ??= CancellationToken.none;

  token.register(
    (state) => (state as HostApplicationLifetime).stopApplication(),
    applicationLifetime,
  );

  var waitForStop = Completer<void>();
  applicationLifetime.applicationStopping.register(
    (state) {
      (state as Completer).complete();
    },
    waitForStop,
  );

  await waitForStop.future;

  // Host will use its default ShutdownTimeout if none is specified.
  // The cancellation token may have been triggered to unblock waitForStop.
  // Don't pass it here because that would trigger an abortive shutdown.
  await stop(CancellationToken.none);
}