How to keep reusing timer - c#

I'm making a simple game on console for practice that requires a time limit each round and I've encountered a problem with trying to make it so I can use timer more than once. I have this:
class Program
{
static Timer timer = new Timer(1000);
static int t = 10;
static void Main(string[] args)
{
timer.Elapsed += Timer_Elapsed1;
timer.Start();
Console.ReadLine();
t = 10;
timer.Start();
Console.ReadLine();
}
My thoughts were that the 2nd timer.Start() would get the same result as the first, but nothing happens.
private static void Timer_Elapsed1(object sender, ElapsedEventArgs e)
{
t--;
Console.WriteLine("Hello!");
if (t == 0)
{
Console.WriteLine("Goodbye!");
timer.Stop();
}
}
Why is the second timer.Start() not doing anything? How do I make it so I can use timer.Start() again and it will do the same thing as the first time? I'm using System.Timers
NVM IT DOES WORK, IM JUST DUMB LOL

Try stopping or disabling the first timer before trying to start a second time.
C# - how do you stop a timer?

I fell compelled to give you some disclaimers:
First, console is not the right Environment for Game Development. Neither is any of the GUI techs. For games you got XNA (pretty dated) and with .NET Core a bunch of new Options. The important thing is that you have a Game Loop of some form. Or at least imitate one.
Secondly, I am unsure how well most Timers work in console apps. Most of them use callbacks wich usually require a MessageQueue - wich is a GUI feature. I guess you could try a Multithreading time, but then you have to relearn everything if you leave Console applications.
As for your code: I am unsure when the Timer tick happens since you specified no interval. But I guess either:
never
after the 2nd timer start

Related

WPF DispatcherTimer Memory Issue

Edit: If useful, this project is on GitHub at https://github.com/lostchopstik/BetterBlync
I am building an application for the Blync status light using their provided API. This application polls the Lync/Skype for Biz client and converts the status to the appropriate light color. All aspects thus far work as expected, however when I leave this program running for an extended period of time, the memory usage grows until a System.OutOfMemory exception occurs.
I have narrowed the problem down to the DispatcherTimer holding the timer in memory and preventing it from being GCed. After reading some things online I found you could manually call for garbage collection, but this is bad practice. Regardless, here is what I have in my code right now:
private void initTimer()
{
timer = new DispatcherTimer();
timer.Interval = new TimeSpan( 0, 0, 0, 0, 200 );
timer.Tick += new EventHandler( Timer_Tick );
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
// Check to see if any new lights are connected
blync.FindBlyncLights();
// Get current status from Lync client
lync.GetStatus();
// Change to new color
setStatusLight();
if ( count++ == 100 )
{
count = 0;
GC.Collect();
}
}
The timer ticks every 200ms. I commented out all methods inside the timer and just let it run empty, and it still burned memory.
I am wondering what the proper way to handle this timer is. I've used the DispatcherTimer in the past and not had this issue.
I would also be open to trying something besides the DispatcherTimer.
If it is also useful, I have been messing with MemProfiler and here as my current graph with manual GC:
http://imgur.com/Iut91mF
It's a little hard to tell without seeing the rest of the code or the class the timer belongs to. I don't see anywhere you call Stop() on the timer. Does it need to be stopped?
You could also keep a local reference to the timer in whatever class you're in and call Start() and Stop() as needed.
If the timer never needs to be stopped and runs indefinitely, I would certainly look at what you're allocating as the timer runs and that's probably where your issue is.

How do I make a "loop" for a game, that runs every (number) of milliseconds?

I've tried to search for this on google and stackoverflow, but I'm not sure what to call it, so I can't find it.
How would I make a "loop" for the C# program, that runs every, say, 100 milliseconds? Similar to what Minecraft calls "ticks", or GameMaker calls "steps".
I can't figure out how to do this. I'm using visual studio, and I have a main window. There are things that I want to execute constantly, so I'm trying to figure out how to make a "step" or "update" function.
If you want it to run for 100 ms you would do this
System.Timers.Timer timer = new System.Timers.Timer(100);
public void Initialize(object sender, EventArgs e)
{
timer.Elapsed+=Elapsed;
}
public void Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//do stuff
}
Something else you can do, however I don't think this one is as efficient
using System.Threading;
Thread th = new Thread(new ThreadStart(delegate
{
while (true)
{
Thread.Sleep(100);
//do stuff
}
}));
Or, you can download monogame to make more elaborate games in c#
http://www.monogame.net/
It has its own gameTime control.
You could use the Timer control which can be set to tick at a given interval. The interval property is in Milliseconds so you would need Timer1.Interval = 100;
Are you thinking of a Timer?
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Generates recurring events in an application.

how to continuously run a c# console application in background

I would like to know how to run a c# program in background every five minute increments. The code below is not what I would like to run as a background process but would like to find out the best possible method to do this using this code so that I can implement it on another code. so this process should run after a five minute increment. I know I could use threads to do so, but dont really now how to implement this. I know this is the best way How to run a console application on system Startup , without appearing it on display(background process)? this to run in the background, but how would I have the code running in five minute increments
class Program
{
static void Main(string[] args)
{
Console.Write("hellow world");
Console.ReadLine();
}
}
This app should run continuously, putting out a message every 5 minutes.
Isn't that what you want?
class Program
{
static void Main(string[] args)
{
while (true) {
Console.Write("hellow world");
System.Threading.Thread.Sleep(1000 * 60 * 5); // Sleep for 5 minutes
}
}
}
Why not just use Windows Task Scheduler?
Set it to run your app at the desired interval. It's perfect for this sort of job and you don't have to mess about with forcing threads to sleep which can create more problems that it solves.
How about using a System.Windows.Threading.DispatcherTimer?
class Program
{
static void Main(string[] args)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 5, 0); // sets it to 5 minutes
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
static void timer_Tick(object sender, EventArgs e)
{
// whatever you want to happen every 5 minutes
}
}
Probably the simplest way to "fire" a new process every X minutes is to use Windows Task Scheduler.
You could of course do something similar programmatically, e.g. create your own service, that starts the console application every X minutes.
All this under assumption you actually want to close the application before the next iteration. Alternatively, you might just keep it active the whole time. You might use one of the timer classes to fire events periodically, or even a Thread.Sleep in a very simplified scenario....

Is there a way to have a countdown timer while waiting for input?

I'm trying to create a simple game that requires the user's input before the timer runs out.
Basically, the page will load with a time, and wait for the user to say the correct answer. If the time runs out, the game is over, but if the user gets it right, he moves on to the next question.
(i've got the speech part worked out, I just need to figure out the timer)
Is there an easy way to accomplish this?
//Add Using Statement
using System.Windows.Threading;
//Create Timer
DispatcherTimer mytimer;
//Setup Timer
myTimer = new DispatcherTimer();
myTimer.Interval = System.TimeSpan.FromSeconds(10);
myTimer.Tick += myTimer_Tick;
// When you type the +=, this method skeleton should come up
// automatically. But type this in if it doesn't.
void myTimer_Tick(object sender, EventArgs e)
{
//This runs when ever the timer Goes Off (In this case every 10 sec)
}
//Run Timer
myTimer.Start()
//Stop Timer
myTimer.Stop()
Does this solve your question?

.NET Windows Service with timer stops responding

I have a windows service written in c#. It has a timer inside, which fires some functions on a regular basis. So the skeleton of my service:
public partial class ArchiveService : ServiceBase
{
Timer tickTack;
int interval = 10;
...
protected override void OnStart(string[] args)
{
tickTack = new Timer(1000 * interval);
tickTack.Elapsed += new ElapsedEventHandler(tickTack_Elapsed);
tickTack.Start();
}
protected override void OnStop()
{
tickTack.Stop();
}
private void tickTack_Elapsed(object sender, ElapsedEventArgs e)
{
...
}
}
It works for some time (like 10-15 days) then it stops. I mean the service shows as running, but it does not do anything. I make some logging and the problem can be the timer, because after the interval it does not call the tickTack_Elapsed function.
I was thinking about rewrite it without a timer, using an endless loop, which stops the processing for the amount of time I set up. This is also not an elegant solution and I think it can have some side effects regarding memory.
The Timer is used from the System.Timers namespace, the environment is Windows 2003. I used this approach in two different services on different servers, but both is producing this behavior (this is why I thought that it is somehow connected to my code or the framework itself).
Does somebody experienced this behavior? What can be wrong?
Edit:
I edited both services. One got a nice try-catch everywhere and more logging. The second got a timer-recreation on a regular basis. None of them stopped since them, so if this situation remains for another week, I will close this question. Thank you for everyone so far.
Edit:
I close this question because nothing happened. I mean I made some changes, but those changes are not really relevant in this matter and both services are running without any problem since then. Please mark it as "Closed for not relevant anymore".
unhandled exceptions in timers are swallowed, and they silently kill the timer
wrap the body of your timer code in a try-catch block
I have seen this before with both timer, and looped services. Usually the case is that an exception is caught that stops the timer or looping thread, but does not restart it as part of the exception recovery.
To your other points...
I dont think that there is anything "elegant" about the timer. For me its more straight forward to see a looping operation in code than timer methods. But Elegance is subjective.
Memory issue? Not if you write it properly. Maybe a processor burden if your Thread.Sleep() isn't set right.
http://support.microsoft.com/kb/842793
This is a known bug that has resurfaced in the Framework more than once.
The best known work-around: don't use timers. I've rendered this bug ineffective by doing a silly "while (true)" loop.
Your mileage may vary, so verify with your combination of OS/Framework bits.
Like many respondents have pointed out exceptions are swallowed by timer. In my windows services I use System.Threading.Timer. It has Change(...) method which allows you to start/stop that timer. Possible place for exception could be reentrancy problem - in case when tickTack_Elapsed executes longer than timer period. Usually I write timer loop like this:
void TimeLoop(object arg)
{
stopTimer();
//Do some stuff
startTimer();
}
You could also lock(...) your main loop to protect against reentrancy.
Interesting issue. If it is truly just time related (i.e. not an exception), then I wonder if you can simply periodically recycle the timer - i.e.
private void tickTack_Elapsed(object sender, ElapsedEventArgs e)
{
CheckForRecycle();
// ... actual code
}
private void CheckForRecycle()
{
lock(someLock) {
if(++tickCount > MAX_TICKS) {
tickCount = 0;
tickTack.Stop();
// re-create timer
tickTack = new Timer(...);
tickTack.Elapsed += ...
tickTack.Start();
}
}
}
You could probably merge chunks of this with the OnStart / OnStop etc to reduce duplication.
Have you checked the error logs? Maybe you run out of timers somehow. Maybe you can create just one timer when you initialize the ArchiveService and skip the OnStart stuff.
I have made exactly the same as you in a few projects but have not had the problem.
Do you have code in the tickTac_Elapsed that can be causing this? Like a loop that never ends or some error that stops the timer, using threads and waiting for ending of those and so on?

Categories