Cooperative cancellation

Component: NServiceBus
NuGet Package: NServiceBus (8-pre)
This page targets a pre-release version. Pre-releases are subject to change and samples are not guaranteed to be fully functional.

Run the solution. A single console application starts up: Server.

Code walk-through

When the endpoint is started a CancellationToken is passed in from a CancellationTokenSource

var tokenSource = new CancellationTokenSource();

var endpointInstance = await Endpoint.Start(endpointConfiguration, tokenSource.Token)

A message is sent to the endpoint once the endpoint starts which triggers a long-running message handler:

public async Task Handle(LongRunningMessage message, IMessageHandlerContext context)
    log.Info($"Received message {message.DataId}. Entering loop.");

        await Task.Delay(2000, context.CancellationToken);
        log.Info("Press any key to cancel the loop and stop the endpoint.");
    } while (!context.CancellationToken.IsCancellationRequested);

Once a key is pressed, the CancellationTokenSource.Cancel method is called to: signal the cancellation token, stop the long running handler, and shut down the endpoint.


Last modified