Created
July 20, 2020 20:54
-
-
Save pablopioli/f7da61e490c575a306501067bfd0fca1 to your computer and use it in GitHub Desktop.
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.Timers; | |
namespace Blazored.Toast | |
{ | |
internal class CountdownTimer : IDisposable | |
{ | |
private Timer _timer; | |
private int _percentComplete; | |
internal Action<int> OnTick; | |
internal Action OnElapsed; | |
internal CountdownTimer(int timeout) | |
{ | |
_timer = new Timer(timeout * 1000) | |
{ | |
Interval = timeout * 1000 / 100, | |
AutoReset = true | |
}; | |
_timer.Elapsed += HandleTick; | |
_percentComplete = 0; | |
} | |
internal void Start() | |
{ | |
_timer.Start(); | |
} | |
private void HandleTick(object sender, ElapsedEventArgs args) | |
{ | |
_percentComplete += 1; | |
OnTick?.Invoke(_percentComplete); | |
if (_percentComplete >= 100) | |
{ | |
OnElapsed?.Invoke(); | |
} | |
} | |
public void Dispose() | |
{ | |
_timer.Dispose(); | |
_timer = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment