How to create a singleton class which runs when ASP.NET WEB FORMS starts (without dependency on the user login)

622 views Asked by At

I have an ASP.NET web form application hosted on IIS.

In the app, I have a code snippet that should make some work on the background from the moment the application starts.

The problem is when I have created the singleton class and initialize it from Global.asax -> Application_Start(), The code runs only when the first user is connecting to the site.

How can I set it to run without any dependency from the user side? Any Idea?

The singleton class example:

public sealed class SingeltonBackgroundWork
{
    private static SingeltonBackgroundWork updater = null;
    private static Timer timer;
    private SingeltonBackgroundWork()
    {
        //Milliseconds * Seconds * Minutes
        timer = new Timer(1000 * 60 * 10);
        timer.Elapsed += new ElapsedEventHandler(OnElapsed);
        timer.AutoReset = true;
        timer.Enabled = true;
    }

    private void OnElapsed(object sender, ElapsedEventArgs e)
    {
        //DO SOME WORK
    }

    public static void InitProcess()
    {
        if (updater == null)
        {
            updater = new SingeltonBackgroundWork();
        }
    }
}

Global.asax Application_Start():

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        SingeltonBackgroundWork.InitProcess();
    }
1

There are 1 answers

0
T.kowshik Yedida On

"The code runs only when the first user is connecting to the site.", because it is written under application_start. Method name clearly says it runs only on application start. If the code needs to be executed per user, session is the option. So, the code must be under Session_Start method.

Reference SO link - https://stackoverflow.com/questions/50136591/application-start-vs-session-start#:~:text=Application_Start%20executes%20just%20once%20when,instantiate%20and%20manage%20visitor%20data.