Windows service timer multithread
I am building a Windows Service that will audit users based on a schedule in a database. The service checks the database for scheduled audits every ten minutes. Once and audit is started, it marks a start time in the database table so it will not start again if it takes longer than ten minutes.
My question is, is the following code acceptable for what I am doing and should I use multithreading every time 10 minutes is elapsed and if so, how would I accomplish this?
My sample code:
protected override void OnStart(string[] args)
{
var aTimer = new Timer(600000);
aTimer.Elapsed += ATimerElapsed;
aTimer.Interval = 600000;
aTimer.Enabled = true;
GC.KeepAlive(aTimer);
}
private static void ATimerElapsed(object sender, ElapsedEventArgs e)
{
try
{
Worker.ProcessSchedul开发者_开发问答edAudits();
}
catch (Exception ex)
{
EventLog.WriteEntry("Application", ex.Message, EventLogEntryType.Error);
}
}
A System.Threading.Timer will use a thread from the Threadpool to run the Elapsed handler(s). So, you're already using multithreading just by using the timer. In fact, ALL timers use a background thread of some kind; they just differ on how they multithread in order to do what makes the most sense for the intended usage.
If you need to run something once every ten minutes, but also make sure that two handlers are never running at the same time, try setting a "CurrentlyRunning" flag in the Elapsed method, and examining it before doing any heavy lifting.
protected override void OnStart(string[] args)
{
var aTimer = new Timer(600000);
aTimer.Elapsed += ATimerElapsed;
aTimer.Interval = 600000;
aTimer.Enabled = true;
GC.KeepAlive(aTimer);
}
private static currentlyRunning;
private static void ATimerElapsed(object sender, ElapsedEventArgs e)
{
if(currentlyRunning) return;
currentlyRunning = true;
try
{
Worker.ProcessScheduledAudits();
}
catch (Exception ex)
{
EventLog.WriteEntry("Application", ex.Message, EventLogEntryType.Error);
}
currentlyRunning = false;
}
Theoretically, this could race, but as you're only kicking off a thread for this event every 10 minutes the odds are EXTREMELY unlikely.
This code already is "using multithreading". Assuming that your Timer
instance is System.Timers.Timer
, your Elapsed
handler will run on a thread pool thread.
If this isn't what you want, you can use the SynchronizingObject
property to modify the dispatch behavior. For more details, read the MSDN documentation.
精彩评论