0
Hello, I’m a beginner and decided to create a stopwatch function to practice some techniques. The timer can mark the time downward (e.g.: 10.9.8.7.6.5) or upward (9.10.11.12), and the user can choose the start and end intervals. However, although my code is working perfectly to time seconds and, in my view, being quite clean and concise, the execution and processing time of the lines of code precludes any attempt to time thousandths with some accuracy. I would like to know if there is any way of optimizing it or if there is some function that I do not know and that could be applied in this case. From now on, thank you.
class Timer
{
private int _delay;
public int Delay { set { _delay = value >= 0 ? value : 0; } }
public void Counting(int initialValue, int finalValue)
{
int start = DateTime.Now.Second + _delay;
int countingValue = initialValue;
int i = 0;
while (initialValue <= finalValue ? countingValue <= finalValue : countingValue >= finalValue)
{
start = start + i == 60 ? - i : start;
if (DateTime.Now.Second == start + i)
{
Display(countingValue);
countingValue = initialValue <= finalValue ? countingValue + 1 : countingValue - 1;
i++;
}
}
}
public void Display(int countingValue)
{
Console.WriteLine(countingValue);
}
}
First, you don’t need a class to do this. A method solves your problem with a small change. Only create classes if you need them. If you don’t have a reason to have one, don’t. Unless you want to do something else, but we can only assess what’s in your code and what you put in there that you want to do. Then, that’s the worst way to try it. It keeps the processor working like crazy for a despicable result. You have some answers here that help: https://answall.com/q/86014/101 and https://answall.com/q/211902/101.
– Maniero
Thank you very much for your reply, @Maniero . Reading the links you suggested, I learned a little about async methods and managed to implement "await Task.Delay();" in my code. The one thing I didn’t understand very well was this question of avoiding creating new classes. It would be possible to create a method alone (without being within a class), or you were referring to placing this method within the class where the Main is?
– Dhonai
C# 9 is totally possible, before that it was possible to create a static class that is not a truth class. And of course it can be next to the
Main()
, but not necessarily.– Maniero