Issue with DispatcherTimer for a Countdown clock - c#

I have started developing a quiz app that will have a 60 second count down for each question. I searched other issues but could not find my specific issue. When the first question is displayed the screen dsplays "60" and the countdown proceeds normally. However, when the second questions is generated (after a button click submit) the counter starts again, but this time uses 2 second intervals. Then when the third question generates after a click, it counts down in 3 second intervals! I then noticed that the timer display starts 1 second less in each question. (ex Question 1 starts with 60, Question 2 starts with 59......)
This is my first time using DispatcherTimer so I'm learning as I go. My goal is for the timer to always countdown in 1 second intervals.
public sealed partial class QuickPage : Page
{
DispatcherTimer timeLeft = new Dispatcher();
int timesTicked = 60;
public void CountDown()
{
timeLeft.Tick += timeLeft_Tick;
timeLeft.Interval = new TimeSpan(0,0,0,1);
timeLeft.Start();
}
public void timeLeft_Tick(object sender, object e)
{
lblTime.Text = timesTicked.ToString();
if (timesTicked > 0)
{
timesTicked--;
}
else
{
timeLeft.Stop();
lblTime.Text = "Times Up";
}
}
}
I then use a button click where if th user is right:
timeLeft.Stop();
timesTicked = 60
QuestionGenerator();
The Question Generator fucntion looks like this:
private void QuestionGenerator()
{
CountDownTimer();
if (iAsked < 6)
{
//Code to generate random question
}
}

Do not subscribe to the DispatcherTimer every time you call CountDown.
DispatcherTimer timeLeft;
int timesTicked = 60;
public QuickPage()
{
timeLeft = new Dispatcher();
timeLeft.Tick += timeLeft_Tick;
timeLeft.Interval = new TimeSpan(0,0,0,1);
}
private void QuestionGenerator()
{
timeLeft.Start();
if (iAsked < 6)
{
//Code to generate random question
}
}

Related

Using a timer and milliseconds to fade a form away but the duration is doubled

I am making my own little custom message box, essentially its just a small box showing up with a message for X amount of time, and then fades away for Y duration.
What is happening tho is that the fade away takes double as long as its supposed to and I cannot figure out why. Can someone look at my code and spot why its taking double the amount of time to fade the form away than it is expected?
//Initiate and set up the message bubble.
public static void InitiateBubble(String displayText, Double showTime = 1000, Double fadeTime = 2000) {
Bubble bubble = new Bubble(displayText);
bubble.showTime = showTime;
bubble.fadeTime = fadeTime;
bubble.Show();
bubble.showTimer = new Timer();
bubble.showTimer.Interval = (int)bubble.showTime;
bubble.showTimer.Tick += bubble.startFadeAway;
bubble.showTimer.Start();
}
//Leaves some time on screen before starting to fade away
private void startFadeAway(object sender, EventArgs e) {
showTimer.Stop();
fadeAwayTimer = new Timer();
fadeAwayTimer.Interval = 10;
fadeAwayTimer.Tick += fadeAway;
fadeAwayTimer.Start();
}
//slowly fades the contorle away until it disapears.
private void fadeAway(object sender, EventArgs e) {
double opacity = Opacity;
opacity -= (10 / fadeTime);
if (opacity < 0) {
Close();
}
else {
Opacity = opacity;
}
}
If the user sets the fade interval to 1 second (1000 milliseconds), and we set the timer interval to 1/10th of a second (100 milliseconds), then we need to fade the opacity by 10% every interval (since the interval is triggered 10 times per second). So we would set Opacity -= .1 on each iteration.
If the user sets the fade interval to 2 seconds (2000 milliseconds), and we still have the timer interval set to 1/10th of a second, then we need to fade the opacity by only 5% every interval, so we would set Opacity -= .05 on each iteration.
Seeing this relationship, we can discover that:
var amountToReduceOpacity = 1.0 / fadeTime * interval;
Note: as γηράσκω δ' αεί πολλά διδασκόμε mentioned above, the resolution on the winform timer is around 17 milliseconds, so if we set it to less than this, the fade will slow down dramatically because we will have calculated the rate for a very fast timer (meaning that we won't fade very much each iteration), but it will execute more slowly. On my machine, setting it to 50 looks just fine.
Now we can use this formula to always fade the form by the correct amount each interval. Here's a sample Form that does basically what you're doing above (note that I dropped a label and two timers on the form, and named them: lblDisplay, showTimer, and fadeTimer):
public partial class Bubble : Form
{
private readonly double amountToReduceOpacity;
private readonly int fadeInterval = 50;
// Custom form constructor takes in all three required settings
public Bubble(string displayText, int showTime, int fadeTime)
{
InitializeComponent();
lblDisplay.AutoSize = true;
lblDisplay.Text = displayText;
lblDisplay.Left = ClientRectangle.Width / 2 - lblDisplay.Width / 2;
lblDisplay.Top = ClientRectangle.Height / 2 - lblDisplay.Height / 2;
showTimer.Interval = showTime;
fadeTimer.Interval = fadeInterval;
amountToReduceOpacity = 1.0 / fadeTime * fadeInterval;
}
// The Shown event starts the first timer
private void Bubble_Shown(object sender, EventArgs e)
{
showTimer.Start();
}
// The shownTimer starts the fadeTimer
private void showTimer_Tick(object sender, EventArgs e)
{
showTimer.Stop();
BackColor = Color.Red; // Just so we see when the fade starts
fadeTimer.Start();
}
// The fade timer reduces opacity on each iteration until it's zero
private void fadeTimer_Tick(object sender, EventArgs e)
{
Opacity -= amountToReduceOpacity;
if (Opacity <= 0) Close();
}
}
Then on the client side we can just do something like:
private void button1_Click(object sender, EventArgs e)
{
Bubble bubble = new Bubble("Help me, I'm Fading!", 1000, 2000);
bubble.Show();
}

Is there a way to Get the 'progress' of an Observable.Timer

Currently I have this working as expected
Observable.Timer(TimeSpan.FromSeconds(5))
.Subscribe(x => MessageBroker.Default.Publish(new Messages.Serve()));
I would like to display a countdown based off this Observables remaining time but can't find a way to access the timers current value.
Is there a way to do this without wrapping the whole thing and keeping track of the progress separately?
When making a timer in Unity always try to use the Unity API first unless there is a great reason not to. If making a count down timer, decrement your timer variable with Time.detalTime every frame. This can be done in the Update or a coroutine function. If you want to be able use multiple instances of this, put it in its own class.
public struct CountDownTimer
{
private static int sTimerID = 0;
private MonoBehaviour monoBehaviour;
public float timer { get { return localTimer; } }
private float localTimer;
public int timerID { get { return localID; } }
private int localID;
public CountDownTimer(MonoBehaviour monoBehaviour)
{
this.monoBehaviour = monoBehaviour;
localTimer = 0;
//Assign timer ID
sTimerID++;
localID = sTimerID;
}
public void Start(int interval, Action<float, int> tickCallBack, Action<int> finshedCallBack)
{
localTimer = interval;
monoBehaviour.StartCoroutine(beginCountDown(tickCallBack, finshedCallBack));
}
private IEnumerator beginCountDown(Action<float, int> tickCallBack, Action<int> finshedCallBack)
{
while (localTimer > 0)
{
localTimer -= Time.deltaTime;
//Notify tickCallBack in each clock tick
tickCallBack(localTimer, localID);
yield return null;
}
//Notify finshedCallBack after timer is done
finshedCallBack(localID);
}
}
Usage:
//Create new Timer
CountDownTimer timer = new CountDownTimer(this);
//What to do each second time tick in the timer
Action<float, int> tickCallBack = (currentTime, timerID) =>
{
Debug.Log("Time Left: " + currentTime + " ID: " + timerID);
};
//What to do when timer changes
Action<int> finshedCallBack = (timeriD) =>
{
Debug.Log("Count Down Timer Done! ID: " + timeriD);
};
//Start Countdown Timer from 5
timer.Start(5, tickCallBack, finshedCallBack);
You can access the timer progress anytime with the CountDownTimer.timer variable if you wish. Although, I prefer to use Action like above and be notified when the progress changes.

wpf Multiple dispatch timer for timer application : Run multiple timer simulteniously

Read multiple stackoverflow, codeproject solution, could not integrate to my problem.
Have a datagrid in a usercontrol which is loaded in a window. Each DataRow in the DataGrid represents a timer setting.
Like:
timer name : Test 1 , Timer : 1h 3m
timer name : Test 2 , Timer : 2h 2m
timer name : Test 3 , Timer : 3h 1m
Selecting a row, clicking on the button Start, Starts the timer of that row. And with dispatcher tick event, it updates the grid I have done till this. Now I have to start another(or two or ...) timer which will do the same at the same time. I am stuck on this. Let me share what I have tried!
btnStartClickEvent in mainwindow.xaml.cs
if (btnStart.Content.ToString() == "Start")
{
if (_AUC == ActiveUserControl.Grid)
{
runningRow = (TaskGridData)_TG.dgEmployee.SelectedItem;
if (runningRow != null)
{
currentlyRunningID.Add(runningRow.ID);
btnStart.Content = "Stop";
//worker.RunWorkerAsync(runningRow);
StartTimer(runningRow);
}
}
}
else if (btnStart.Content.ToString() == "Stop")
{
btnStart.Content = "Start";
StopTimer();
}
private DateTime TimerStart { get; set; }
private void StartTimer(TaskGridData tgd)
{
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
TimerStart = DateTime.Now;
dispatcherTimer.Start();
//worker.RunWorkerAsync();
//string etime = DateTime.Now.Second.ToString();
}
private void StopTimer()
{
dispatcherTimer.Stop();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
var currentValue = DateTime.Now - TimerStart;
runningRow.Duration = DurationValueToString(currentValue);
temp = (List<TaskGridData>)_TG.dgEmployee.ItemsSource;
foreach (TaskGridData item in temp)
{
if (item.ID == runningRow.ID)
{
item.Duration = DurationValueToString(DurationStringToVlaue(item.Duration) - DurationStringToVlaue(runningRow.Duration));
break;
}
}
//_TG.dgEmployee.ItemsSource = null;
//_TG.dgEmployee.ItemsSource = temp;
Thread NewThreadforStartProcessAfterTraining = new Thread(() => UpdateGrid());
NewThreadforStartProcessAfterTraining.IsBackground = true;
NewThreadforStartProcessAfterTraining.SetApartmentState(ApartmentState.STA);
NewThreadforStartProcessAfterTraining.Start();
}
private void UpdateGrid()
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
_TG.dgEmployee.ItemsSource = null;
_TG.dgEmployee.ItemsSource = temp;
}));
}
I know this code is for single timer. If I click a 2nd row and try to start timer, then it gets error in tick event, running row is found null.
I am wondering how can I keep this code and make it work for multiple timer. May be multithreading. A guide to do that, will be very helpful.
Thread NewThreadforStartProcessAfterTraining = new Thread(() => UpdateGrid());
NewThreadforStartProcessAfterTraining.IsBackground = true;
NewThreadforStartProcessAfterTraining.SetApartmentState(ApartmentState.STA);
NewThreadforStartProcessAfterTraining.Start();
All the above part where you start a new STA thread is unneeded and wrong in this context, since you can't update the visual tree in this way.
You can find a correct example of using a STA thread in one of my previous answers: https://stackoverflow.com/a/42473167/6996876
Try to understand the concept of thread affinity in WPF.
You simply need an UpdateGrid() where you have to delegate UI work to the dispatcher.
Furthermore, passing an argument to the Tick event is already explained here: https://stackoverflow.com/a/16380663/6996876
In your case you may want to change the current unique runningRow so that it's passed to the event instead.

WPF Dispatchertimer is not stopping, nor restarting

I want a DispatcherTimer to restart everytime the conditions are not met. Only when the if-condition is met for 5 seconds, the method can continue.
How should I stop the Dispatchertimer? The timeToWait variable is set to 3000, that works as intended.
Below is the code in C#. It is not responding as I want. It only starts, but never stops or restarts. I am making a WPF application.
dispatcherTimerStart = new DispatcherTimer();
if (average >= centerOfPlayingField - marginOfDetection && average <= centerOfPlayingField + marginOfDetection)
{
dispatcherTimerStart.Interval = TimeSpan.FromMilliseconds(timeToWait);
dispatcherTimerStart.Tick += new EventHandler(tick_TimerStart);
startTime = DateTime.Now;
dispatcherTimerStart.Start();
} else
{
dispatcherTimerStart.Stop();
dispatcherTimerStart.Interval = TimeSpan.FromMilliseconds(timeToWait);
}
private void tick_TimerStart(object sender, EventArgs args)
{
DispatcherTimer thisTimer = (DispatcherTimer) sender;
thisTimer.Stop();
}
you need to preserve the dispatcherTimer that enter your if block because in your else block you are stopping the new instance of DispatcherTimer not the one that entered the if block.
take a class level field
DispatcherTimer preservedDispatcherTimer=null;
var dispatcherTimerStart = new DispatcherTimer();
if (average >= centerOfPlayingField - marginOfDetection && average <= centerOfPlayingField + marginOfDetection)
{
**preservedDispatcherTimer = dispatcherTimerStart;**
dispatcherTimerStart.Interval = TimeSpan.FromMilliseconds(timeToWait);
dispatcherTimerStart.Tick += new EventHandler(tick_TimerStart);
startTime = DateTime.Now;
dispatcherTimerStart.Start();
}
//use preservedDispatcherTimer in else
else if(preservedDispatcherTimer!=null)
{
preservedDispatcherTimer.Stop();
preservedDispatcherTimer.Interval = TimeSpan.FromMilliseconds(timeToWait);
}

C# Set duration and play sounds stored in an arraylist consecutively

I have the following Play method for playing musical notes stored in an arraylist:
public void Play(Duration d){
int duration = 1;
if (d == Duration.SemiBreve)
{
duration = 16;
}
else if (d == Duration.DotMin)
{
duration = 10;
}
else if (d == Duration.minim)
{
duration = 8;
}
else if (d == Duration.Crotchet)
{
duration = 4;
}
else if (d == Duration.Quaver)
{
duration = 2;
}
else if (d == Duration.SemiQuaver)
{
duration = 1;
}
player = new SoundPlayer();
player.SoundLocation = "pathToLocation";
//set timer
time = new Timer();
time.Tick += new EventHandler(clockTick);
time.Interval = duration * 150;
player.Play();
time.Start();
}
When I call the method with a button:
private void PlayButton_Click(object sender, EventArgs e)
{
//Loops through the collection and plays each note one after the other
foreach (MusicNote music in this.staff.Notes)
{
music.Play(music.Dur)
}
}
Only the last note gets played. With PlaySync() all the notes get played but the duration isn't recognized. I also tried using threads like so:
foreach (MusicNote music in this.staff.Notes)
{
Thread t = new Thread(playMethod=>music.Play(music.Dur));
t.Start();
t.Join();
}
But it doesn't work either. Any suggestions as to how I can get the files to play consecutively like with PlaySync but using their set duration?
You don't wait for the timer anywhere. So in practice all notes get played almost simultaneously, causing just the last one to be effectively audible.
UPDATE: Using the System.Timers.Timer class the way to go is registering a handler for the Elapsed event and playing the notes one-by-one in the event handler. This way you avoid freezing the UI.
Another option is playing in a background thread and the using Thread.Sleep to wait. Here you will have to make sure the thread is stopped according to the state of the UI (i.e. the use closes the current dialog etc.).
In either case to avoid race conditions you will have to solve concurrent access to staff.Notes or make a copy of it for the sake of playing it.

Categories