Customize the Lifecycle of a Web or Worker role in .NET

Important

Cloud Services (classic) is now deprecated for all customers as of September 1st, 2024. Any existing running deployments will be stopped and shut down by Microsoft and the data will be permanently lost starting October 2024. New deployments should use the new Azure Resource Manager based deployment model Azure Cloud Services (extended support).

When you create a worker role, you extend the RoleEntryPoint class, which provides methods for you to override that let you respond to lifecycle events. For web roles, this class is optional, so you must use it to respond to lifecycle events.

Extend the RoleEntryPoint class

The RoleEntryPoint class includes methods that are called by Azure when it starts, runs, or stops a web or worker role. You can optionally override these methods to manage role initialization, role shut down sequences, or the execution thread of the role.

When extending RoleEntryPoint, you should be aware of the following behaviors of the methods:

  • The OnStart method returns a boolean value, so it's possible to return false from this method.

    If your code returns false, the role process is abruptly terminated, without running any shutdown sequence you may have in place. In general, you should avoid returning false from the OnStart method.

  • Any uncaught exception within an overload of a RoleEntryPoint method is treated as an unhandled exception.

    If an exception occurs within one of the lifecycle methods, Azure raises the UnhandledException event, and then the process is terminated. After your role goes offline, Azure restarts it. When an unhandled exception occurs, the Stopping event isn't raised, and the OnStop method isn't called.

If your role doesn't start, or is recycling between the initializing, busy, and stopping states, your code may be throwing an unhandled exception within one of the lifecycle events each time the role restarts. In this case, use the UnhandledException event to determine the cause of the exception and handle it appropriately. Your role may also be returning from the Run method, which causes the role to restart. For more information about deployment states, see Common Issues Which Cause Roles to Recycle.

Note

If you are using the Azure Tools for Microsoft Visual Studio to develop your application, the role project templates automatically extend the RoleEntryPoint class for you, in the WebRole.cs and WorkerRole.cs files.

OnStart method

The OnStart method is called when your role instance is brought online by Azure. While the OnStart code is executing, the role instance is marked as Busy and the load balancer doesn't direct any external traffic to it. You can override this method to perform initialization work, such as implementing event handlers and starting Azure Diagnostics.

If OnStart returns true, the instance is successfully initialized and Azure calls the RoleEntryPoint.Run method. If OnStart returns false, the role terminates immediately, without executing any planned shutdown sequences.

The following code example shows how to override the OnStart method. This method configures and starts a diagnostic monitor when the role instance starts and sets up a transfer of logging data to a storage account:

public override bool OnStart()
{
    var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

    config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Error;
    config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(5);

    DiagnosticMonitor.Start("DiagnosticsConnectionString", config);

    return true;
}

OnStop method

The OnStop method is called after Azures takes a role instance offline and before the process exits. You can override this method to call code required for your role instance to cleanly shut down.

Important

Code running in the OnStop method has a limited time to finish when it is called for reasons other than a user-initiated shutdown. After this time elapses, the process is terminated, so you must make sure that code in the OnStop method can run quickly or tolerates not running to completion. The OnStop method is called after the Stopping event is raised.

Run method

You can override the Run method to implement a long-running thread for your role instance.

Overriding the Run method isn't required; the default implementation starts a thread that sleeps forever. If you do override the Run method, your code should block indefinitely. If the Run method returns, the role is automatically recycled; in other words, Azure raises the Stopping event and calls the OnStop method so that your shutdown sequences may be executed before the role is taken offline.

Implementing the ASP.NET lifecycle methods for a web role

You can use the ASP.NET lifecycle methods, in addition to the methods provided by the RoleEntryPoint class, to manage initialization and shutdown sequences for a web role. This approach may be useful for compatibility purposes if you're porting an existing ASP.NET application to Azure. The ASP.NET lifecycle methods are called from within the RoleEntryPoint methods. The Application_Start method is called after the RoleEntryPoint.OnStart method finishes. The Application_End method is called before the RoleEntryPoint.OnStop method is called.

Next steps

Learn how to create a cloud service package.