XAML DispatcherTimer Interval Too Slow - c#

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.

Related

C# DispatchTimer WPF Countdown Timer

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'').

Displaying next sampling time date and time without freezing WPF form in C#

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.

C# - Win Form stopping Timer tick

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''");
}

DispatcherTimer will increasing Interval for every time it's used

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.

Timer Interval Calling Long Method

What would happen with the code below if Execute() takes, say, 3000ms to finish, but is being called every 1000ms due to the timer interval?
Timer _timer = new Timer();
private void setupTimer()
{
_timer.Tick += new EventHandler(pollingTimeElapsed);
_timer.Interval = 1000;
_timer.Enabled = true;
_timer.Start();
}
private void pollingTimeElapsed(object sender, EventArgs e)
{
Execute();
}
EDIT: I am using System.Windows.Forms.Timer, since System.Timers.Timer doesn't have .Tick
I'm assuming you are using the System.Timers.Timer class.
Since AutoReset has the default value (which is True), the Elapsed event will be fired for each time 1000ms has elapsed.
If you want to fire the event only one time, set AutoReset to False.
If you do not want to fire the event while your execute-code is running, do the following:
Timer _timer = new Timer();
private void setupTimer() {
_timer.Tick += new EventHandler(pollingTimeElapsed);
_timer.Interval = 1000;
_timer.Enabled = true;
_timer.Start();
}
private void pollingTimeElapsed(object sender, EventArgs e) {
try {
_timer.Stop()
Execute();
} finally {
_timer.Start()
}
}

Categories