8

Whenever a Windows Azure role is stopped its OnStop() method is invoked. Turns out that there's RoleEnvironment.Stopping event that is triggered before OnStop() is invoked. MSDN says this event is the right place for role clean shutdown code.

What's the difference between the two? Why would I put role clean shutdown code in Stopping event and not in OnStop() method override?

David Makogon
  • 69,407
  • 21
  • 141
  • 189
sharptooth
  • 167,383
  • 100
  • 513
  • 979

3 Answers3

4

Besides the fact that the event mechanism provides a flexible way to attach handlers, while the OnStop method has to be defined directly on the class derived from RoleEntryPoint, one relevant difference is this:

The Stopping event is not raised when the virtual machine of the role
instance is rebooted.

So the stopping event will not be raised, for instance, when the VM is rebooted for guest OS upgrade.

Another difference is this:

Code running in the OnStop method has 5 minutes to finish when it is called
for reasons other than a user-initiated shutdown.

While there is no mention in the documentation that the Stopping event has such a limit.

Source:

Fernando Correia
  • 21,803
  • 13
  • 83
  • 116
  • 1
    If you look into Azure processes logs you'll see that the 5 minutes limit is for the whole stopping sequence, so that's just MSDN being slightly wrong. – sharptooth Dec 07 '12 at 09:38
2

Events allow other subscribers in other classes to perform some action, whereas the method allows the subclass author such as yourself to place it in the actual class and (for example) modify which events get raised.

Alex Norcliffe
  • 2,439
  • 2
  • 17
  • 21
1

Brent Stineman (Windows Azure MVP) recently blogged about the RoleEntryPoint and related start/run/stop sequence, and describes both Stopping and OnStop in the sequence descriptions.

David Makogon
  • 69,407
  • 21
  • 141
  • 189
  • 1
    Well, he says that the event is triggered before `OnStop()` is invoked. I don't see anything beyond that in that post. – sharptooth Nov 22 '11 at 15:23
  • 4
    As I understand it, and admittedly I haven't focused on testing this, the Stopping is your first alert to clean up. So at this point you may stop taking on more work (pulling from a queue, shutting down your internal endpoint listener). Its also more of an async event. The OnStop is your final effort to get stopped and for which you only have 5 minutes to act on and its called directly by the Azure Fabric agent. This all does need more exploration but just simply hasn't been very high on my priority list. It could even be that these two items run in different security contexts. – BrentDaCodeMonkey Nov 22 '11 at 16:53