Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Cooperative cancellation

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)
    .ConfigureAwait(false);

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.");

    do
    {
        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.

tokenSource.Cancel();

Last modified