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.
- Worker Role assembly is loaded and surfed for a class that derives from RoleEntryPoint. This class is instantiated.
- RoleEntryPoint.OnStart() is called.
- RoleEntryPoint.Run() is called.
- If the RoleEntryPoint.Run() method exits, the RoleEntryPoint.OnStop() method is called .
- 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.
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.
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:
- WaWebHost process is started.
- Hostable Web Core is activated.
- Web role assembly is loaded and RoleEntryPoint.OnStart() is called.
- Global.Application_Start() is called.
- The web application runs…
- Global.Application_End() is called.
- RoleEntryPoint.OnStop() is called.
- Hostable Web Core is deactivated.
- 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).