在 .NET 中自定义 Web 角色或辅助角色的生命周期Customize the Lifecycle of a Web or Worker role in .NET

在创建辅助角色时,需要扩展 RoleEntryPoint 类,重写该类提供的方法可以响应生命周期事件。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. 此类对于 Web 角色而言是可选的,因此,必须将它用于响应生命周期事件。For web roles this class is optional, so you must use it to respond to lifecycle events.

扩展 RoleEntryPoint 类Extend the RoleEntryPoint class

RoleEntryPoint 类包含由 Azure 在启动、运行或停止 Web 角色或辅助角色时调用的方法。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 shutdown sequences, or the execution thread of the role.

在扩展 RoleEntryPoint 时,应该了解方法的以下行为:When extending RoleEntryPoint, you should be aware of the following behaviors of the methods:

  • OnStartOnStop 方法返回布尔值,因此,可以从这些方法返回 false。The OnStart and OnStop methods return a boolean value, so it is possible to return false from these methods.

    如果代码返回 false,则该角色进程将突然终止,而不会运行可能拥有的任何关闭序列。If your code returns false, the role process is abruptly terminated, without running any shutdown sequence you may have in place. 一般来说,应该避免从 OnStart 方法返回 false。In general, you should avoid returning false from the OnStart method.

  • RoleEntryPoint 方法重载中未捕获的任何异常都被视为未经处理的异常。Any uncaught exception within an overload of a RoleEntryPoint method is treated as an unhandled exception.

    如果某个生命周期方法中发生异常,则 Azure 将引发 UnhandledException 事件,然后进程会终止。If an exception occurs within one of the lifecycle methods, Azure will raise the UnhandledException event, and then the process is terminated. 角色脱机后,Azure 会将它重启。After your role has been taken offline, it will be restarted by Azure. 如果出现未经处理的异常,则不会引发 Stopping 事件,并且不会调用 OnStop 方法。When an unhandled exception occurs, the Stopping event is not raised, and the OnStop method is not called.

如果角色未启动,或者在初始化、繁忙和停止状态之间循环,可能是因为每次角色重启生命周期事件时,代码都引发了未经处理的异常。If your role does not 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. 在这种情况下,请使用 UnhandledException 事件确定异常的原因并采用适当的方法进行处理。In this case, use the UnhandledException event to determine the cause of the exception and handle it appropriately. 角色也可能会从 Run 方法返回,从而促使角色重启。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.

备注

如果当前使用 Azure Tools for Microsoft Visual Studio 开发应用程序,则角色项目模板将自动在 WebRole.cs 和 WorkerRole.cs 文件中扩展 RoleEntryPoint 类。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 方法OnStart method

当 Azure 使角色实例联机时,就会调用 OnStart 方法。The OnStart method is called when your role instance is brought online by Azure. OnStart 代码执行时,角色实例被标记为“忙”,并且负载均衡器不会将外部流量引导到该角色。While the OnStart code is executing, the role instance is marked as Busy and no external traffic will be directed to it by the load balancer. 可以重写此方法以执行初始化工作,例如实现事件处理程序和启动 Azure 诊断You can override this method to perform initialization work, such as implementing event handlers and starting Azure Diagnostics.

如果 OnStart 返回 true,则该实例已成功初始化,并且 Azure 已调用 RoleEntryPoint.Run 方法。If OnStart returns true, the instance is successfully initialized and Azure calls the RoleEntryPoint.Run method. 如果 OnStart 返回 false,则角色将立即终止,而不执行任何计划中的关闭序列。If OnStart returns false, the role terminates immediately, without executing any planned shutdown sequences.

下面的代码示例演示如何重写 OnStart 方法。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 方法OnStop method

OnStop 方法在 Azure 使角色实例脱机之后并且在进程退出之前被调用。The OnStop method is called after a role instance has been taken offline by Azure and before the process exits. 可以重写此方法调用角色实例所需的代码,从而彻底关闭此角色实例。You can override this method to call code required for your role instance to cleanly shut down.

重要

如果出于某些原因而不是用户启动的关闭而调用 OnStop 方法,则此方法中运行的代码必须在有限的时间内完成。Code running in the OnStop method has a limited time to finish when it is called for reasons other than a user-initiated shutdown. 这段时间过后,进程将被终止,因此,必须确保 OnStop 方法中的代码能够快速运行或者不必完全运行。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. 引发 Stopping 事件后,会调用 OnStop 方法。The OnStop method is called after the Stopping event is raised.

Run 方法Run method

可以重写 Run 方法,为角色实例实现长时间运行的线程。You can override the Run method to implement a long-running thread for your role instance.

重写 Run 方法不是必需的;默认实现可以启动一个永远休眠的线程。Overriding the Run method is not required; the default implementation starts a thread that sleeps forever. 如果重写 Run 方法,则代码可能会被无限期阻止。If you do override the Run method, your code should block indefinitely. 如果 Run 方法返回,角色将正常自动回收;也就是说,Azure 将引发 Stopping 事件并调用 OnStop 方法,因此,在角色脱机之前可能执行了关闭序列。If the Run method returns, the role is automatically gracefully 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.

为 Web 角色实现 ASP.NET 生命周期方法Implementing the ASP.NET lifecycle methods for a web role

除了 RoleEntryPoint 类提供的方法以外,还可以使用 ASP.NET 生命周期方法管理 Web 角色的初始化和关闭序列。You can use the ASP.NET lifecycle methods, in addition to those provided by the RoleEntryPoint class, to manage initialization and shutdown sequences for a web role. 如果要将现有的 ASP.NET 应用程序迁移到 Azure,此方法可能有利于解决兼容性问题。This may be useful for compatibility purposes if you are porting an existing ASP.NET application to Azure. ASP.NET 生命周期方法将从 RoleEntryPoint 方法中调用。The ASP.NET lifecycle methods are called from within the RoleEntryPoint methods. Application_Start 方法将在 RoleEntryPoint.OnStart 方法结束后调用。The Application_Start method is called after the RoleEntryPoint.OnStart method finishes. Application_End 方法将在 RoleEntryPoint.OnStop 方法调用前调用。The Application_End method is called before the RoleEntryPoint.OnStop method is called.

后续步骤Next steps

了解如何创建云服务包Learn how to create a cloud service package.