RoleEntryPoint.OnStop Method
Runs code when a role instance is to be stopped.
Namespace: Microsoft.WindowsAzure.ServiceRuntime
Assembly: Microsoft.WindowsAzure.ServiceRuntime (in Microsoft.WindowsAzure.ServiceRuntime.dll)
Assembly: Microsoft.WindowsAzure.ServiceRuntime (in Microsoft.WindowsAzure.ServiceRuntime.dll)
Override the OnStop method to run code when the role instance is stopped. The following code example shows how to override the OnStop method:
public override void OnStop() { try { // Add code here that runs when the role instance is to be stopped } catch (Exception e) { Trace.WriteLine("Exception during OnStop: " + e.ToString()); // Take other action as needed. } }
Note |
|---|
| 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. |
A web role can include initialization code in the ASP.NET Application_End method instead of the OnStop method. The Application_Start method is called before the Stopping event is raised or the OnStop method is called. For more information about the Application_End method, see ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0.
For more information about life cycle management, see Overview of Building an Application that Runs in a Hosted Service.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Development Platforms
Windows Vista, Windows 7 and Windows Server 2008Target Platforms
Stopping sequence
Is is useful to know that OnStop happens after the Stopping event has fired (http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.serviceruntime.roleenvironment.stopping.aspx), and that the Role Instance is removed from the load balancer before the Stopping event fires. So when your OnStop is processing, you know the load balancer has stopped sending you work, and you can potentially allow graceful shutdown by letting active work drain before returning from OnStop.
- 4/11/2012
- codingoutloud
To keep your role alive...
When I experimented (SDK 1.4), my role stopped as soon as OnStop() exited. Thus if you want to give your main loop in Run() a chance to gracefully exit, keep the OnStop() thread busy until then.
- 11/11/2011
- oliverbock
Time allowed for stopping
...seems to be 5 minutes (http://social.msdn.microsoft.com/Forums/en-US/windowsazuredevelopment/thread/e68edf21-e25c-46ec-9a59-dfc97466169e).
- 11/11/2011
- oliverbock
Note