patterncsharpMinor
PreWarmCache for MVC Application with Stopwatch Infinite Loop
Viewed 0 times
infinitestopwatchmvcapplicationwithloopprewarmcachefor
Problem
I used the information from the article "Auto-Start ASP.NET Applications (VS 2010 and .NET 4.0 Series)" to create a background task that runs on an infinite loop. Ultimately, this program is going to be consuming a REST API to get data from a remote web site and insert records into my database. For the time being, I am just doing a basic insert.
public class PreWarmCache : System.Web.Hosting.IProcessHostPreloadClient
{
private static BackgroundTaskContext db = new BackgroundTaskContext();
private static Timer _timer;
public void Preload(string[] parameters)
{
// Perform initialization and cache loading logic here...
try
{
var doStuff = new DoStuff();
doStuff.DoStuffName = "Test from PRELOAD INIT " + DateTime.Now;
db.DoStuffs.Add(doStuff);
db.SaveChanges();
}
catch
{
}
var timeInMilliseconds = 0;
_timer = new Timer(Callback, null, timeInMilliseconds, Timeout.Infinite);
}
public static void Callback(Object state)
{
var timeInMilliseconds = 5000;
Stopwatch watch = new Stopwatch();
watch.Start();
// Update the database
try
{
var doStuff = new DoStuff();
doStuff.DoStuffName = "Test from CALLBACK " + DateTime.Now;
db.DoStuffs.Add(doStuff);
db.SaveChanges();
}
catch
{
}
_timer.Change(Math.Max(0, timeInMilliseconds - watch.ElapsedMilliseconds), Timeout.Infinite);
}
}Solution
There are some things that you could have done better certainly.
My first pick is the class name
In this class you seem to be appending the current time to the property
You also seem to have one of the most evil bad practises of programming - the empty catch block. Be sure to, at least, log the exception somewhere.
My first pick is the class name
DoStuff. Please try pick a more meaningful name like Action or Task. In this class you seem to be appending the current time to the property
DoStuffName (which should also be renamed accordingly). You could pass the name in the constructor and append the current time instead, like:public class Task{
public Task(string name){
Name = name + " " + DateTime.Now;
}
public string Name{
get; private set;
}
}You also seem to have one of the most evil bad practises of programming - the empty catch block. Be sure to, at least, log the exception somewhere.
Code Snippets
public class Task{
public Task(string name){
Name = name + " " + DateTime.Now;
}
public string Name{
get; private set;
}
}Context
StackExchange Code Review Q#55059, answer score: 2
Revisions (0)
No revisions yet.