I followed an example from Head First C# on DispatcherTimer.
First time I press the button the ticker will increase by 1 second, but the next time I click on the button the ticker will increase by 2 seconds for every second/tick. Third time ticker increases with 3 seconds and so on (1 second is added for every button press).
Why is that and how to i "reset" the ticker Interval so it will only increase by 1 second every time?
Here is code:
DispatcherTimer timer = new DispatcherTimer();
private void Button_Click_1(object sender, RoutedEventArgs e)
{
timer.Tick += timer_Tick;
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Start();
CheckHappiness();
}
int i = 0;
void timer_Tick(object sender, object e)
{
ticker.Text = "Tick #" + i++;
}
private async void CheckHappiness()
{
... code ..
timer.Stop();
}
}
}
Cheers!
timer.Tick += timer_Tick;
This line adds the method to the eventhandler everytime you press the button; in which you do an i++ which increases i by one.
When you have two methods doing that at the same time (since the timer ticks on your interval) then you get an increase by two every tick of the timer.
Related
I have a WPF application that includes a countdown timer, I'm stuck with the formatting part of it, I have little to no experience with programming and this is my first time using c#. I want to countdown from 15 minutes using DispatchTimer, but as of now, my timer only counts down from 15 seconds, any ideas?
My countdown timer so far:
public partial class MainWindow : Window
{
private int time = 15;
private DispatcherTimer Timer;
public MainWindow()
{
InitializeComponent();
Timer = new DispatcherTimer();
Timer.Interval = new TimeSpan(0,0,1);
Timer.Tick += Timer_Tick;
Timer.Start();
}
void Timer_Tick(object sender, EventArgs e) {
if (time > 0)
{
time--;
TBCountDown.Text = string.Format("{0}:{1}", time / 60, time % 60);
}
else {
Timer.Stop();
}
}
The output looks like this:
A better approach would be to do it with a TimeSpan rather than an int with a number. Setting the TimeSpan value in the following application will do the countdown as I want.
TimeSpan.FromMinutes for minutes
TimSpan.FromSeconds for seconds
You can check here for more detailed information.
public partial class MainWindow : Window
{
DispatcherTimer dispatcherTimer;
TimeSpan time;
public MainWindow()
{
InitializeComponent();
time = TimeSpan.FromMinutes(15);
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
dispatcherTimer.Tick += DispatcherTimer_Tick;
dispatcherTimer.Start();
}
private void DispatcherTimer_Tick(object sender, EventArgs e)
{
if (time == TimeSpan.Zero) dispatcherTimer.Stop();
else
{
time = time.Add(TimeSpan.FromSeconds(-1));
MyTime.Text = time.ToString("c");
}
}
}
Xaml Code
<Grid>
<TextBlock Name="MyTime" />
</Grid>
You initialise the DispatchTimer with an interval of 1 second: Timer.Interval = new TimeSpan(0,0,1);
And every TimerTick you decrement your timefield.
So, timeshould start of with the total number of seconds you want to count down. If you start with 15, your countdown timer will count down from 15 seconds to zero.
If you want it to count down for 15minutes, you have to initialise time to 900 (15 x 60'').
I am writing a code in WPF & C# to display next sampling time in Date and time format.
For example, if sampling time is one minute and current time is 08:00 - the next sampling time should show 08:01, Next sampling time is displayed once 08:01 has passed.
I have tried using dispatcherTimer and sleep thread.
But when I use the whole WPF form freezes until next update.
Could you please help me?
code ->
public float samplingTime = 1;
public MainWindow()
{
InitializeComponent();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
tboxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
void timer_Tick(object sender, EventArgs e)
{
System.Threading.Thread.Sleep((int)samplingTime*1000);
tboxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
}
}
I'd use the DispatcherTimer for such a problem:
public float samplingTime = 1;
public MainWindow()
{
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
tboxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
}
Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs.
This is my implementation of a Win Form app that has a countdown timer:
readonly DateTime myThreshold;
public Form1()
{
InitializeComponent();
myThreshold = Utils.GetDate();
Timer timer = new Timer();
timer.Interval = 1000; //1 second
timer.Tick += new EventHandler(t_Tick);
timer.Start();
//Threshold check - this only fires once insted of each second
if (DateTime.Now.CompareTo(myThreshold) > 0)
{
// STOP THE TIMER
timer.Stop();
}
else
{
//do other stuff
}
}
void t_Tick(object sender, EventArgs e)
{
TimeSpan timeSpan = myThreshold.Subtract(DateTime.Now);
this.labelTimer.Text = timeSpan.ToString("d' Countdown - 'hh':'mm':'ss''");
}
The wanted behavior is to stop the timer and the tick function when the threshold is reached.
This now does not happens because the check is only executed once since it is placed in the Form1 initialization.
Does exist a way to add this check in a way to immediately stop the Timer once a condition has been meet?
If we define timer as a class field (so it can be accessed from all methods in the class), then we can just add the check to the Tick event itself, and stop the timer from there:
private Timer timer = new Timer();
void t_Tick(object sender, EventArgs e)
{
// Stop the timer if we've reached the threshold
if (DateTime.Now > myThreshold) timer.Stop();
TimeSpan timeSpan = myThreshold.Subtract(DateTime.Now);
this.labelTimer.Text = timeSpan.ToString("d' Countdown - 'hh':'mm':'ss''");
}
I am using a timer to run a method every 16 minutes. I also want to run a second method every minute for 15 minutes in-between.
Below is the code I am using:
int count = 0;
private void cmdGo_Click(object sender, EventArgs e)
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 960000; // specify interval time - 16 mins
t.Tick += new EventHandler(timer_Tick);
t.Start();
}
void timer_Tick(object sender, EventArgs e)
{
RunMethod1();
while(count < 15)
{
//waiting for 60 seconds
DateTime wait = DateTime.Now;
do
{
Application.DoEvents();
} while (wait.AddSeconds(60) > DateTime.Now);
RunMethod2();
}
}
The above code seems to work fine but the ‘do while’ loop to wait for 60 seconds is very CPU heavy.
I tried to use Thread.Sleep(60000) but this freezes up the Interface and also tried to add a second timer within timer_Tick but this doesn’t seem possible. Can a second timer be added within the EventHandler of the first?
Is there any other method to achieve this without being so CPU intensive?
Thanks!
Warren
NOTE: Sorry guys, there was a typo in my original post. The 60 second wait do, while loop should have been within the while < 15 loop. Just updated the code snippet.
So:
RunMethod1() should be executed every 16 mins
RunMethod2() should be executed every 1 min (15 times) in between the 16 min tick
It would make more sense to have a counter to store how many times the clock has gone off. Then set your timer interval to fire once a minute so not doing anything in between...
That way you could just do...
private int Counter;
private void cmdGo_Click(object sender, EventArgs e)
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 60000; // specify interval time - 1 minute
t.Tick += new EventHandler(timer_Tick);
t.Start();
}
// Every 1 min this timer fires...
void timer_Tick(object sender, EventArgs e)
{
// If it has been 16 minutes then run RunMethod1
if (++Counter >= 16)
{
Counter = 0;
RunMethod1();
return;
}
// Not yet been 16 minutes so just run RunMethod2
RunMethod2();
}
You could await a task Delay so the UI will keep responding
async void timer_Tick(object sender, EventArgs e)
{
RunMethod1();
while (count < 15)
{
//waiting for 60 seconds
await Task.Delay(60000);
RunMethod2();
}
}
I need to count very fast for my Windows 8 Store Application. So i set the interval to 10 Ticks. As we have 10,000,000 ticks per second that should be enough. But i only get around 30 ticks as a result. How do i get a faster timer?
My code for the timer (and control timer):
int GLOBAL_counter = 0;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromTicks(10);
timer.Tick += timer_Tick;
timer.Start();
DispatcherTimer timerControl = new DispatcherTimer();
timerControl.Interval = TimeSpan.FromSeconds(1);
timerControl.Tick += timer_Tick_timerControl;
timerControl.Start();
}
private void timer_Tick(object sender, object e)
{
GLOBAL_counter++;
}
private void timer_Tick_timerControl(object sender, object e)
{
Label1.Text += GLOBAL_counter.ToString() + "\r\n";
GLOBAL_counter = 0;
}
From MSDN description of DispatcherTimer class:
Timers are not guaranteed to execute exactly when the time interval
occurs, but they are guaranteed to not execute before the time
interval occurs. This is because DispatcherTimer operations are placed
on the Dispatcher queue like other operations. When the
DispatcherTimer operation executes is dependent on the other jobs in
the queue and their priorities.