You can quite easy replace your Thread
code with a System.Threading.Timer
based version.
I refactored your code in your GutHub: https://github.com/CrazyDanyal1414/mathstester.git
public class RunWithTimer
{
private DateTime _finish { get; set; }
public bool IsTimeLeft { get=> _finish > DateTime.Now; }
private System.Threading.Timer _timer = null;
private void TimerCallback(object state)
{
string timeLeft = (_finish - DateTime.Now).ToString(@"hh\:mm\:ss");
WriteToScreen($"Time Remaining: {timeLeft}", true);
if (!this.IsTimeLeft)
{
_timer.Dispose();
}
}
public RunWithTimer(int numberOfSeconds)
{
_finish = DateTime.Now.AddSeconds(numberOfSeconds);
_timer = new Timer(TimerCallback, null, TimeSpan.Zero, TimeSpan.FromSeconds(1.0));
}
public void StopTimer(int numberOfQuestionsLeft)
{
if (numberOfQuestionsLeft == 0)
{
_timer.Dispose();
}
}
}
Ideally your RunWithTimer
would implement IDisposable
since it holds a variable of IDisposable
. You'd then remove the StopTimer
code and Dispose()
of the it once the questions are finished.