Startup and Shutdown Sequence

Component: NServiceBus
NuGet Package: NServiceBus (7.x)

Code walk-through

The sample illustrates the order of startup and shutdown steps for an NServiceBus endpoint. All usages of the public extension points API are stored in the ExtensionPoints folder of the project.


For each step in the process, there is a corresponding log entry written both to the console and a text file.

static class Logger
    static ILog log = LogManager.GetLogger(typeof(Logger));
    public static string OutputFilePath;
    static object locker = new object();

    static Logger()
        OutputFilePath = Path.GetFullPath(@"..\StartupShutdownSequence.txt");
        AppDomain.CurrentDomain.ProcessExit += Exit;
        File.AppendAllText(OutputFilePath, "startcode");
        File.AppendAllText(OutputFilePath, " StartupShutdownSequence\r\n");

    static void Exit(object sender, EventArgs e)
        File.AppendAllText(OutputFilePath, "endcode");

    public static void WriteLine(string message)
        message = $"Thread:{Thread.CurrentThread.ManagedThreadId} {message}\r\n";
        lock (locker)
            File.AppendAllText(OutputFilePath, message);


Console program

The main section of the console Program configures and starts the endpoint while logging all these actions.

Logger.WriteLine("Starting configuration");
var endpointConfiguration = new EndpointConfiguration("Samples.StartupShutdown");

Logger.WriteLine("Calling Endpoint.Start");
var endpointInstance = await Endpoint.Start(endpointConfiguration)
// simulate some activity
await Task.Delay(500)

Logger.WriteLine("Endpoint is processing messages");
Logger.WriteLine("Calling IEndpointInstance.Stop");
await endpointInstance.Stop()

The resulting order

In some versions of NServiceBus, certain extension points are executed on separate threads.
Thread:1 Starting configuration
Thread:1 Calling Endpoint.Start
Thread:1 Inside INeedInitialization.Customize
Thread:1 Inside WantToRunBeforeConfigurationIsFinalized.Run
Thread:1 Inside Feature.Setup
Thread:1 Inside INeedToInstallSomething.Install
Thread:1 Inside FeatureStartupTask.OnStart
Thread:5 Endpoint is processing messages
Thread:5 Calling IEndpointInstance.Stop
Thread:5 Inside FeatureStartupTask.OnStop
Thread:5 Finished

Related Articles

  • Installers
    Installers ensure endpoint-specific artifacts are installed and configured during endpoint startup.

Last modified