Created
December 26, 2011 11:29
-
-
Save sriki77/1520952 to your computer and use it in GitHub Desktop.
Timer & Deferred Eval & GC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading; | |
namespace TimerDeferredEval | |
{ | |
class JobScheduler : IDisposable | |
{ | |
private static readonly TimeSpan DueTime = new TimeSpan(0, 0, 0, 5); | |
private static readonly TimeSpan Period = new TimeSpan(0, 24, 0); | |
private readonly IEnumerable<TimerCallback> _jobs; | |
private IEnumerable<Timer> _timers; | |
public JobScheduler(IEnumerable<TimerCallback> jobs) | |
{ | |
_jobs = jobs; | |
} | |
public void Start() | |
{ | |
_timers = _jobs.Select(job => | |
{ | |
Console.Error.WriteLine("Timer Created..."); | |
return new Timer(job, null, DueTime, Period); | |
}); // Deferred Execution | |
_timers.Count(); // Eager Evaluation | |
Console.Error.WriteLine(_timers.GetType()); | |
} | |
public void Dispose() | |
{ | |
foreach (var timer in _timers) | |
{ | |
timer.Dispose(); | |
} | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
JobScheduler scheduler = new JobScheduler(new List<TimerCallback>{DoWorkOnTimer}); | |
scheduler.Start(); | |
GC.Collect(); | |
Thread.Sleep(10000); | |
scheduler.Dispose(); | |
} | |
static void DoWorkOnTimer(Object data) | |
{ | |
Console.Error.WriteLine("Timer Fired..."); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class JobScheduler : IDisposable | |
{ | |
private static readonly TimeSpan DueTime = new TimeSpan(0, 10, 0); | |
private static readonly TimeSpan Period = new TimeSpan(0, 24, 0); | |
private readonly IEnumerable<TimerCallback> _jobs; | |
private IEnumerable<Timer> _timers; | |
public JobScheduler(IEnumerable<TimerCallback> jobs) { _jobs = jobs;} | |
public void Start() { | |
_timers = _jobs.Select(job => new Timer(job, null, DueTime, Period) }); // Loc 1. | |
_timers.Count(); // Loc 2. } | |
public void Dispose() { | |
foreach (var timer in _timers) timer.Dispose(); // Loc 3. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment