Skip to main content

Lifecycle of Worker Roles (RoleEntryPoint)

In this post we will talk about 3 methods that are available in the RoleEntryPoint class for Web and Worker Roles (especially Worker Roles)

  • OnStart
  • Run
  • OnStop

This 3 methods are called in different moment of the lifecycle of a Worker Role. Each of them has a clear scope and output.

OnStart
This method is called automatically when the instance of Worker Role is initialized. It is used to initialized the context or prepare the instance before executing the task.
This method returns a bool value that it is used to tell the system if the initialization was made with success or not. On the happy case the return value should be true. If an error occurs or the initialization fails, that the false value should be returned. When OnStart methods returns false, the Run method will not be called and the instance will be 'restarted' - No other methods will be called.

Run
The Run method is used to execute the batch operation or the logic that is necessary to be executed by the Worker Role. We should 'block' the code to not exist from this method as long as we want to keep our instance alive.
This method is called only when OnStart methods returns true. When we exit from the Run method, the OnStop method will be called and worker role will be restarted.

OnStop
This method is used to make the cleanup sequence of our system. For example deallocate resources or commit some changes or logs.
This method is called only when the no exception is triggered by Run or OnStart method.

Below you can find the lifecycle flow.


Let's take a look on the following code:

    public class WorkerRole : RoleEntryPoint
    {
        private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);

        public override void Run()
        {
            Logger.Debug(LoggingAction.StartingWorkerRole, "Foo.Workers.SU is running");

            try
            {
                RunAsync(cancellationTokenSource.Token).Wait();
            }
            finally
            {
                runCompleteEvent.Set();
            }
        }

        public override bool OnStart()
        {
            bool reFoolt = base.OnStart();

            Logger.Debug(LoggingAction.StartingWorkerRole, "Foo.Workers.SU has been started");

            ObjectFactory.InitializeContainer(new DependencyInstaller());

            var rp = ObjectFactory.GetObject<IPRP>();            
            rp.StartListeningAsync().Wait();            

            return reFoolt;
        }

        public override void OnStop()
        {
            Logger.Debug(LoggingAction.StoppingWorkerRole, "Foo.Workers.SU is stopping");

            cancellationTokenSource.Cancel();
            runCompleteEvent.WaitOne();

            base.OnStop();

            Logger.Debug(LoggingAction.StoppingWorkerRole, "Foo.Workers.SU has stopped");
        }

        private async Task RunAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {                
                await Task.Delay(1000);
            }
        }
    }

Looking over the above code, we observe that no logic is done on Rum method. Not only we initialize the object factory but we also start listening to a queue in the OnStart method. Because of this the Run method is not used and our Worker Role will be in a 'transition' phase all the time.
What we should keep in OnStart method? The initialization of object factory can be keeped in this method. Also, if we would have some initialization on the logger side, that we should keep it in this place.
What we should not keep in OnStart method? We should move the start listening to our our queue from OnStart method to Run. That is a piece of code that is long running and should be in the Run.

    public class WorkerRole : RoleEntryPoint
    {
        private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);

        public override void Run()
        {
            Logger.Debug(LoggingAction.StartingWorkerRole, "Foo.Workers.SU is running");

            try
            {
                RunAsync(cancellationTokenSource.Token).Wait();
            }
            finally
            {
                runCompleteEvent.Set();
            }
        }

        public override bool OnStart()
        {
            bool reFoolt = base.OnStart();
      
            Logger.Debug(LoggingAction.StartingWorkerRole, "Foo.Workers.SU has been started");
      
      try
      {
        ObjectFactory.InitializeContainer(new DependencyInstaller());            
      }
      catch(Exception ex)
      {
        Logger.Exception(ex);
        reFoolt = false;
      }

            return reFoolt;
        }
    
    public void Run()
    {
      var rp = ObjectFactory.GetObject<IPRP>();            
            rp.StartListeningAsync().Wait();            
    }
    

        public override void OnStop()
        {
            Logger.Debug(LoggingAction.StoppingWorkerRole, "Foo.Workers.SU is stopping");

            cancellationTokenSource.Cancel();
            runCompleteEvent.WaitOne();

            base.OnStop();

            Logger.Debug(LoggingAction.StoppingWorkerRole, "Foo.Workers.SU has stopped");
        }

        private async Task RunAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {                
                await Task.Delay(1000);
            }
        }
    }

In conclusion, there are two important things that we should remember:

  • OnStart should only initialize and configure our system
  • Run method is used for processing and log running tasks

Comments

Popular posts from this blog

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

[Post-Event] Codecamp Conference Cluj-Napoca - Nov 19, 2016

Last day I was invited to another Codecamp Conference, that took place in Cluj-Napoca. Like other Codecamp Conferences, the event was very big, with more than 1.000 participants and 70 sessions. There were 10 tracks in parallel, so it was pretty hard to decide at  what session you want to join.
It was great to join this conference and I hope that you discovered something new during the conference.
At this event I talked about Azure IoT Hub and how we can use it to connect devices from the field. I had a lot of demos using Raspberry PI 3 and Simplelink SensorTag. Most of the samples were written in C++ and Node.JS and people were impressed that even if we are using Microsoft technologies, we are not limited to C# and .NET. World and Microsoft are changing so fast. Just looking and Azure IoT Hub and new features that were launched and I'm pressed (Jobs, Methods, Device Twin).
On backend my demos covered Stream Analytics, Event Hub, Azure Object Storage and DocumentDB.

Title:
What abo…