My timer 'Elapsed' event fires twice when the program is started. The only assignment of the 'Elapsed' event handler is in 'Main' method. Is there something that I'm doing wrong?
//class level clock
public static System.Timers.Timer Clock;
static void Main(string[] args)
{
Clock = new System.Timers.Timer();
Clock.Elapsed += new ElapsedEventHandler(Clock_Elapsed);
Clock.AutoReset = false;
Clock.Interval = timerInterval; //this needs to be in milliseconds!
Clock.Enabled = true;
//run infinite loop until q is pressed
while (Console.Read() != 'q')
{}
}
static void Clock_Elapsed(object sender, ElapsedEventArgs e)
{
Clock.Stop();
//do some stuff
Clock.Start();
}
UPDATE:
The AutoReset provided by #fparadis2 fixed the firing twice. The base issue was that my timer interval was set to 30 milliseconds instead of 30000 milliseconds(30 seconds) so that the event was double firing.
If timerInverval is small enough, it might be possible that the Elapsed event is fired twice before you get the chance to stop the clock. You should do
Clock.AutoReset = false;
in order to be notified only once each time you start the timer.
As specified in the Timer Class documentation:
If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant.
You may also consider checking this pattern.
Related
The method below processing rectangles for the objects identified in findPedestrian() method. I have assigned 'rectCount' variable to show the rectangle count on every each frame. And 'maxCount' variable shows the maximum number of rectangles the count while the process.
private Image<Bgr, Byte> imagingPedestrian(Image<Bgr, Byte> image)
{
System.Drawing.Rectangle[] results = pedestrianDetection.findPedestrian(image);
//System.Drawing.Rectangle[] results2 = vehicleDetection.findVehicle(image);
foreach (Rectangle rect in results)
{
CvInvoke.Rectangle(image, rect, new Bgr(Color.Red).MCvScalar);
rectCount = results.Count();
label1.Text = rectCount.ToString();
if(rectCount > maxCount1)
{
maxCount1 = rectCount;
label8.Text = maxCount1.ToString();
}
else
{
label8.Text = maxCount1.ToString();
}
}
return image;
}
In this question what i want to get is get the rectangle count for every 10 seconds. After 10 seconds the maxCount variable should get reset. Then it should show the maximum rectangle count within next 10 seconds. Like wise it should run iterately within every 10 seconds. Is there anyway to implement it..
Thanks in Advance..
If I understand you correctly, you need to use System.Timer class.
Example from MSDN:
using System;
using System.Timers;
public class Example
{
private static System.Timers.Timer aTimer;
public static void Main()
{
SetTimer();
Console.WriteLine("\nPress the Enter key to exit the application...\n");
Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
Console.ReadLine();
aTimer.Stop();
aTimer.Dispose();
Console.WriteLine("Terminating the application...");
}
private static void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
}
}
// The example displays output like the following:
// Press the Enter key to exit the application...
//
// The application started at 09:40:29.068
// The Elapsed event was raised at 09:40:31.084
// The Elapsed event was raised at 09:40:33.100
// The Elapsed event was raised at 09:40:35.100
// The Elapsed event was raised at 09:40:37.116
// The Elapsed event was raised at 09:40:39.116
// The Elapsed event was raised at 09:40:41.117
// The Elapsed event was raised at 09:40:43.132
// The Elapsed event was raised at 09:40:45.133
// The Elapsed event was raised at 09:40:47.148
//
// Terminating the application...
As you can see, you create a timer, set AutoReset to true so it resets each time when achieving the needed value, and also subscribe your method to event so each time when the timer passes it will execute needed code.
Just apply the same approach to your application and your problem should be solved.
Add a timer to your form. You can drag it from the toolbox onto your form, or as the documentation demonstrates, you can just declare it in your form. You can set the Interval property to 10000 (that's 10 seconds in milliseconds) and set Enabled to true or call the Start() method.
Then add a handler for the Tick event. That event gets raised every time the interval elapses. Within that handler you can perform your updates.
I'm trying to get more familiar with eventhanlders, but my current even only updates once, I want it to update until I close the application.
This is my code:
private static event EventHandler Updater;
Updater += Program_updater;
Updater.Invoke(null, EventArgs.Empty);
Application.Run();
private static void Program_updater(object sender, EventArgs e)
{
KeyUtils.Update();
Framework.Update();
}
But like I said, it will only update once, I want it to update until I close my application. I know I can just do a While(true) but I rather not.
I think you want a Timer here:
Timer aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += Program_updater;
// Have the timer fire repeated events (true is the default)
aTimer.AutoReset = true;
// Start the timer
aTimer.Enabled = true;
Specify callback:
private void Program_updater(Object source, System.Timers.ElapsedEventArgs e)
{
KeyUtils.Update();
Framework.Update();
}
Now every 2 seconds (or specify any other interval) callback OnTimedEvent will be called.
It is absolutely normal that your event is fired only once because the application starts only once.
What you acctualy need is to set up a timer and do some work on its tick.
Please have a look on example in answer for that question Simple example of the use of System. Timers. Timer in C#
Well it only updates once since you only invoke it once (I don't really get the context where your code runs since you both declare a static variable and invokes it on the same scope which is impossible).
If you want something to occur periodically you should use Timer, or in some cases AutoResetEvent/ManualResetEvent.
EventHandlers should be used only when you work as event driven which mean you want your handler to invoke When something happens
Here an example for [System.Timers.Timer][2] with your handler:
//Invoke every 5 seconds.
Timer timer = new Timer(5000);
//Add your handler to the timer invocation list.
timer.Elapsed += Program_updater;
//Start the timer.
timer.Start();
Also you need Program_update's signature to look like that:
private void Program_updater(object source, ElapsedEventArgs e)
How do I execute an infinite loop in C# with a 1 minute delay per iteration?
Is there any way to do it without using some kind of variable with x++ and setting x to some incredibly large number?
Solution1 :
If you want to wait for 1 minute without hanging your Main Thread, it is good to use Timer Control.
Step 1: You need to Subscribe to the Timer Tick event.
Step 2: Set the Interval property of the Timer to 60000 milliseconds for raising the event for every Minute.
Step 3: In Tick Event Handler just do ehatever you want to perform.
Step 4: you can Call the timer1.Stop() method whenever you want to stop the timer.
Note : if you don't stop the timer it becomes infinite.
if you want to stop the timer you can call timer1.Stop();
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
timer1.Interval=60000;//one minute
timer1.Tick += new System.EventHandler(timer1_Tick);
timer1.Start();
private void timer1_Tick(object sender, EventArgs e)
{
//do whatever you want
}
Solution 2:
EDIT : From the below comments : if the OP(Original Poster) is Trying to run this from Console Application System.Timers.Timer can be used
Note : instead of Handling Tick Event , OP has to handle the Elapsed Event.
Complete Code:
class Program
{
static System.Timers.Timer timer1 = new System.Timers.Timer();
static void Main(string[] args)
{
timer1.Interval = 60000;//one minute
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
timer1.Start();
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
static private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
//do whatever you want
Console.WriteLine("I'm Inside Timer Elapsed Event Handler!");
}
}
while (true)
{
System.Threading.Thread.Sleep(60000);
}
Now if we assume you don't want this thread to block and you're ok dealing with threading concerns, you can do something like this:
System.Threading.Tasks.Task.Run(() =>
{
while (true)
{
// do your work here
System.Threading.Thread.Sleep(60000);
}
});
The Task will put your work on a ThreadPool thread, so it runs in the background.
You can also look at a BackgroundWorker if that's more geared toward what you want.
for(;;)
{
//do your work
Thread.Sleep(60000);
}
This is not optimal but does exactly what it's asked.
From a similar question on MSDN:
>
System.Threading.Thread.Sleep(5000);
this codes make your application waiting for 5 seconds.
Change the number as necessary for the amount of time you want to sleep for (for one minute, this would be 60000).
You can put this where you want in your while loop
while(true){
Sleep(60000);}
This would be a blocking call, so you would want to put it on its own thread or any kind of UI that you would have would hang badly.
Sleep is in the System.Threading.Thread namespace.
"Robot Game" is the first basic game I developed. The Magenta '#' character is an enemy and it is supposed have a random movement in this map, but its random movement is too fast and I tried to use Threading but it effects all characters' speed. Now, I need To call the "Enemy" method every 100 milliseconds.
Robot game Image:
You can use System.Timer. However, be forewarned that these timers might not be as accurate as you may desire. You'll never easily get a fully-accurate timer on a non-realtime OS such as Windows, but if you want better timer accuracy, a Multimedia timer might help.
System.Timer example from MSDN:
public class Timer1
{
private static System.Timers.Timer aTimer;
public static void Main()
{
// Normally, the timer is declared at the class level,
// so that it stays in scope as long as it is needed.
// If the timer is declared in a long-running method,
// KeepAlive must be used to prevent the JIT compiler
// from allowing aggressive garbage collection to occur
// before the method ends. You can experiment with this
// by commenting out the class-level declaration and
// uncommenting the declaration below; then uncomment
// the GC.KeepAlive(aTimer) at the end of the method.
//System.Timers.Timer aTimer;
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
//GC.KeepAlive(aTimer);
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}
I have a Console App and in the main method, I have code like this:
Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(time_Elapsed);
I only want the timer to run once so my idea is that I should stop the timer in the time_Elapsed method. However, since my timer exists in Main(), I can't access it.
You have access to the Timer inside of the timer_Elapsed method:
public void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Timer timer = (Timer)sender; // Get the timer that fired the event
timer.Stop(); // Stop the timer that fired the event
}
The above method will stop whatever Timer fired the Event (in case you have multiple Timers using the same handler and you want each Timer to have the same behavior).
You could also set the behavior when you instantiate the Timer:
var timer = new Timer();
timer.AutoReset = false; // Don't reset the timer after the first fire
A little example app:
static void Main(string[] args)
{
int seconds = 2;
Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(MyHandler);
time.Start();
Console.ReadKey();
}
private static void MyHandler(object e, ElapsedEventArgs args)
{
var timer = (Timer) e;
timer.Stop();
}
I assume that you're using System.Timers.Timer rather than System.Windows.Forms.Timer?
You have two options.
First, as probably the best, is to set the AutoReset property to false. This should do exactly what you want.
time.AutoReset = false;
The other option is to call Stop in the event handler.
You may also use the System.Threading.Timer. Its constructor takes two time-related parameters:
The delay before the first "tick" (due time)
The period
Set the period to Timeout.Infinite to prevent from firing again.