Search code examples
c#azureazure-web-roles

When using WebRole.cs to run custom code in "OnStart()", what is the recommended way to call base.OnStart()?


When using WebRole.cs to configure IIS, what is the recommended way to call base.OnStart()?

public class WebRole : Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint
    {
        public override bool OnStart()
        {
            RunMyCode(); 
            return base.OnStart();
        }
    }

or

public class WebRole : Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint
    {
        public override bool OnStart()
        {
            var result = base.OnStart();
            if (result == true) { RunMyCode(); } 
            return result;
        }
    }

In other words, "does it make sense to take the return value from the base class into consideration?".

I have (I think) experienced behaviour where sometimes the base function must have returned false and my code was never was called.


Solution

  • As per official documentation, the call to base.OnStart is the last statement of the method. These methods are provided just as API. RoleEntryPoint is an abstract class with default one-line implementations (or no implementations at all). Also per same documentation, you will see that if you return False, your role instance will be stopped (thus leading to role recycling and unable to start). And last per docu:

    In general, you should avoid returning false from the OnStart method.

    If you take a look (with .NET decompiler of your choice) at the source code for RoleEntryPoint, you will discover that default implementation of OnStart just returns true:

    using System.Threading;
    
    namespace Microsoft.WindowsAzure.ServiceRuntime
    {
      public abstract class RoleEntryPoint
      {
        public virtual bool OnStart()
        {
          return true;
        }
    
        public virtual void Run()
        {
          Thread.Sleep(-1);
        }
    
        public virtual void OnStop()
        {
        }
      }
    }
    

    It is with v.2.4 of SDK. And has been like that since early 1.xx versions.