When a role (work or website) is requested for graceful closure (because it is reduced or because you asked for a reallocation) OnStop calls the RoleEntryPoint class method. This is the same class that the Run method has, which probably either contains your loop or calls the code containing this loop.
A few things to note here: OnStop has 5 minutes to actually stop, after which the process is simply killed. If you need to call something else to disconnect asynchronously, you need to keep the thread in OnStop busy, waiting for this other process to shut down. After the execution left OnStop, the platform suggests that the machine might be shut down.
If you need to gracefully stop processing, but you do not need to turn off the computer, you can put the parameter in the service configuration file, which you can update to indicate that the work should be done or a note. So, for example, a bool that says "ProcessQueues". Then, in your onStart in RoleEntryPoint, you fire up the RoleEnvironmentChanging event. The event handler then looks for a RoleEnvironmentConfigurationSettingChange method, and then checks the ProcessQueues bool. If true, it either starts or continues processing; if it is false, it stops processing gracefully. Then you can change the configuration to control when everything works or not. This is one way to manage this, and there are many others, depending on how quickly you need to stop processing, etc.
source share