Created
September 14, 2014 07:28
-
-
Save tvolodimir/7f993af8a5ea30a22a55 to your computer and use it in GitHub Desktop.
TimeAction Wrapper
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.Threading; | |
using System.Threading.Tasks; | |
using System.Timers; | |
using Timer = System.Timers.Timer; | |
public class TimerAction | |
{ | |
private readonly Action action; | |
private readonly Timer timer; | |
private bool stopInvoked = false; | |
private bool stopped = true; | |
private bool inAction = false; | |
private readonly ManualResetEvent mre = new ManualResetEvent(true); | |
public TimerAction(Action action, int intervalMilliseconds) | |
{ | |
this.action = action; | |
this.timer = new Timer {Interval = intervalMilliseconds}; | |
this.timer.Elapsed += timer_Elapsed; | |
} | |
public void Start() | |
{ | |
lock (this) | |
{ | |
if (stopped) | |
{ | |
stopped = false; | |
stopInvoked = false; | |
if (!inAction) | |
{ | |
mre.Reset(); | |
timer.Start(); | |
} | |
} | |
else if (stopInvoked) | |
{ | |
// disable this feature (mre set only on "stopped" and after stop invoking, mre not setted - its a problem maybe) | |
// Timer cancel stoping and start | |
//stopInvoked = false; | |
} | |
} | |
} | |
public void StopInvoke() | |
{ | |
lock (this) | |
{ | |
if (stopped) return; | |
if (stopInvoked) return; | |
stopInvoked = true; | |
timer.Stop(); | |
if (!inAction) | |
{ | |
stopped = true; | |
OnStopped(); | |
} | |
} | |
} | |
public Task Stop() | |
{ | |
StopInvoke(); | |
return new TaskFactory().StartNew(() => | |
{ | |
mre.WaitOne(); | |
}); | |
} | |
private void timer_Elapsed(object sender, ElapsedEventArgs e) | |
{ | |
lock (this) | |
{ | |
timer.Stop(); | |
if (stopped) return; | |
if (stopInvoked) | |
{ | |
stopped = true; | |
OnStopped(); | |
return; | |
} | |
inAction = true; | |
} | |
try | |
{ | |
action(); | |
} | |
catch (Exception exception) | |
{ | |
} | |
lock (this) | |
{ | |
inAction = false; | |
if (stopped) return; | |
if (stopInvoked) | |
{ | |
stopped = true; | |
OnStopped(); | |
} | |
else | |
{ | |
timer.Start(); | |
} | |
} | |
} | |
private void OnStopped() | |
{ | |
mre.Set(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment