Windows Azure RoleEntryPoint Method Call Order

I saw an internal discussion that had some information I thought would be useful to share.  It’s about how some of the methods in RoleEntryPoint get called.

In the case of a Worker Role, the RoleEntryPoint class is the class you derive to write your code.  When you create a new Worker Role project in Visual Studio, you’ll see that the project contains one code file and in that code file there is a class called WorkerRole that derives from RoleEntryPoint.

Worker Role Call Order:

WaWorkerHost process is started.

  1. Worker Role assembly is loaded and surfed for a class that derives from RoleEntryPoint.  This class is instantiated.
  2. RoleEntryPoint.OnStart() is called.
  3. RoleEntryPoint.Run() is called. 
  4. If the RoleEntryPoint.Run() method exits, the RoleEntryPoint.OnStop() method is called .
  5. WaWorkerHost process is stopped. The role will recycle and startup again.

For step 1 above, Windows Azure only loads one assembly and takes the first class that derives from RoleEntryPoint that it finds.  Visual Studio knows which assembly implements RoleEntryPoint based on the reference to the project under the Roles node.

image

That reference is a project to project reference that is passed through to packaging.  This puts a file called __entrypoint.txt in the Service Package than contains the name of the assembly that has a class that derives from RoleEntryPoint. 

image 

In the case of a Web role, a RoleEntryPoint derived class is actually not required.  That said, in the Visual Studio web role templates, we add a file called WebRole.cs that includes an implementation of OnStart() specifically to add template code to show you how to startup the the Diagnostic Monitor and to show you how to hook into configuration setting changes. (i.e. when a new serviceconfiguration.cscfg file is uploaded to the cloud)

Web Role Call Order:

  1. WaWebHost process is started.
  2. Hostable Web Core is activated.
  3. Web role assembly is loaded and RoleEntryPoint.OnStart() is called.
  4. Global.Application_Start() is called.
  5. The web application runs…
  6. Global.Application_End() is called.
  7. RoleEntryPoint.OnStop() is called.
  8. Hostable Web Core is deactivated.
  9. WaWebHost process is stopped.

You can implement a RoleEntryPoint.Run() method in a WebRole, it’ll get called on a new foreground thread that executes in parallel with RoleEntryPoint.OnStart().

Thing is, if you exit from the RoleEntryPoint.Run() method, (the default implementation just waits on an infinite Thread.Sleep()) your role is going to recycle – so just be aware of that consequence, almost certainly not what you want in a web role (the role will be offline while it starts up again).