Moin,
ich komme bei meinem kleinen Vorhaben nicht weiter und bräuchte etwas Hilfestellung. Ich möchte mehrere Countdowns hintereinander ausführen. Momentan rast das Programm durch alle Zeitsetzungen durch. Wie halte ich es an, ohne es in einer While-Schleife gefangen zu halten? Ich habe es mit einer While-Schleife versucht, anstatt des Timers, aber dann wurde die GUI nicht aktualisiert.
Momentan sieht das alles wie folgt aus:
using System;
namespace Training_Timer
{
class Training
{
// class vars
private System.Windows.Forms.Timer aTimer;
private System.Media.SoundPlayer timeOutSignal;
private int timerCounter;
private TrainingPlan plan;
private System.Windows.Forms.Label uiLabel;
public Training()
{
_init();
InitCountdown();
}
// init
private void _init()
{
aTimer = new System.Windows.Forms.Timer();
timeOutSignal = new System.Media.SoundPlayer(@"F:\workspace\Visual Studio 2017\Projects\Training Timer\signal01.wav");
timerCounter = 0;
// avoid crash
plan = new TrainingPlan();
uiLabel = new System.Windows.Forms.Label();
}
public void Start()
{
foreach (TrainingExercise exercise in plan)
{
for (int i = 0; i < exercise.Sets; i++)
{
Countdown(exercise.Duration);
if (exercise.Pause != 0)
Countdown(exercise.Pause);
}
}
}
// timer
private void InitCountdown(int interval)
{
aTimer.Tick += new EventHandler(OnTimedEvent);
aTimer.Interval = interval;
}
private void InitCountdown()
{
InitCountdown(1000);
}
private void Countdown(int duration)
{
//UpdateUITimer(duration);
timerCounter = duration;
aTimer.Enabled = true;
}
private void UpdateUITimer(int counter)
{
uiLabel.Text = TimeSpan.FromSeconds(counter).ToString("mm':'ss");
}
// events
private void OnTimedEvent(object source, EventArgs e)
{
if(timerCounter == 0)
{
timeOutSignal.Play();
aTimer.Enabled = false;
}
UpdateUITimer(timerCounter);
timerCounter--;
}
// getter & setter
public void SetPlan(TrainingPlan trainingPlan)
{
plan = trainingPlan;
}
public void SetUILabel(System.Windows.Forms.Label label)
{
uiLabel = label;
}
}
}
Besser und einfacher: Reactive Extensions.
Reactive Extensions (Rx) – Part 4 – Replacing Timers
Spart Dir hier 90% Quellcode.
- performance is a feature -
Microsoft MVP - @Website - @AzureStuttgart - github.com/BenjaminAbt - Sustainable Code