1

I have a variable (custom object) in a singleton that I want to update based on a timer.

So, every 30 minutes I would get the new values from the database and update this variable. Eventual consistency between various servers is the only thing that's important - so if one server has a bit older value because the singleton timer is not synced that isn't an issue.

I was thinking of spawning off a thread in the singleton constructor with a timer and updating the variable based on that timer.

I'm not sure where in the application lifecycle a thread started from a singleton could be terminated. Is this the correct architectural approach to this? Or, is there something else I should be doing?

tereško
  • 58,060
  • 25
  • 98
  • 150
rksprst
  • 6,471
  • 18
  • 54
  • 81

2 Answers2

3

This is something that might look easy at the first place but could become very complex task because working with recurring background tasks in ASP.NET is not something that is recommended to be done. The reason is that the application domain could be unloaded by the web server in certain circumstances that are out of your control such as a period of inactivity on the site, some CPU/memory thresholds are reached, ... Of course when your application is unloaded from memory all threads that you might have spawn to perform this background task will simply stop.

Or, is there something else I should be doing?

Yes, there are probably other approaches depending on what you are trying to achieve (where and why do you need this variable and how it is supposed to be used, ...).

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

Why not just update it when it's requested once it's out of date? This way you don't waste time updating it if it's not being used. Like this...

public class MyClass
{
    private static MyClass sInstance
    private static DateTime sInstanceLastUpdated = DateTime.MinValue;
    public static MyClass Instance
    {
        get
        {
            if(sInstance == null || DateTime.Now.Subtract(sInstanceLastUpdated).TotalMinutes > 30)
            {
                sInstance = new MyClass();
                // initialize.
            }
            return sInstance;
        }
    }
}
Brian
  • 37,399
  • 24
  • 94
  • 109