AI agents: use the documentation index at llms.txt to locate machine-readable pages. This section is indexed by https://docs.particular.net/samples/llms.txt. The markdown version of this page is served as plain text. An MCP server at /mcp serves the same content via the search_docs and read_doc tools; it is read-only and needs no credentials. Markdown versions of documentation pages are available by appending .md to the page URL. Directory URLs use index.md. They are served as text/plain because some retrieval backends reject text/markdown.

Cooperative cancellation

Component:
NServiceBus
NuGet Package:
NServiceBus 10.x

This sample demonstrates graceful shutdown of its host via cooperative cancellation by signaling a cancellation token to abort a simulated long-running async operation inside a handler.

To get started run the solution. A single console application starts up: Server.

Code walk-through

When the endpoint is started, a message is sent to the endpoint, which triggers a long-running message handler. The handler enters an infinite loop, logging a message every two seconds, by calling the async Task.Delay() operation. The CancellationToken provided by the message handling context object is passed to Task.Delay() to cancel the delay operation if the context.CancellationToken.IsCancellationRequested property is set to true.

public async Task Handle(LongRunningMessage message, IMessageHandlerContext context)
{
    logger.LogInformation("Received message {MessageDataId}. Entering loop.", message.DataId);

    while (true)
    {
        logger.LogInformation("Handler still running. Press any key to forcibly stop the endpoint.");
        await Task.Delay(2000, context.CancellationToken);
    }
}

Once a key is pressed, a CancellationTokenSource is created, scheduling a cancel operation after one second. This cancellation token is then passed to the endpoint's stop command for cooperative cancellation. (See the blog post Cancellation in NServiceBus 8.)

var tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(TimeSpan.FromSeconds(1));
await host.StopAsync(tokenSource.Token);

After one second, a signal is sent to the cancellation token, terminating the long running handler and forcibly shutting down the endpoint. If the handler were to complete its operation before the cancel signal is sent to the cancellation token, then the endpoint would gracefully shutdown.