Hello,
As you said, you have resolved the problem.
I was using this
private async void StartIncrementingRemovedCo2Kilograms(Turbine turbine) {
while (isRunning) {
await Task.Delay(1000); // Increment every second
// Increment RemovedCo2Kilograms by 0.0007
UpdateRemovedCo2Kilograms(turbine, IncrementValue);
}
}
private void UpdateRemovedCo2Kilograms(Turbine turbine, double increment) {
turbine.RemovedCo2Kilograms += increment;
// Round to 3 decimal places
turbine.RemovedCo2Kilograms = RoundToDecimals(turbine.RemovedCo2Kilograms, 3);
Debug.WriteLine($"Updated RemovedCo2Kilograms: {turbine.RemovedCo2Kilograms}");
}
private double RoundToDecimals(double value, int decimals = 2) {
return Math.Round(value, decimals);
}
}
What I should have done is
public TurbinesService(DeviceLanguageService deviceLanguageService, IDispatcher application) {
_deviceLanguageService = deviceLanguageService;
_dispatcher = application;
InitializeTimer(); // Just initialize the timer, do not start it here
}
// Initialize the timer
private void InitializeTimer() {
_timer = _dispatcher.CreateTimer(); // Use the injected dispatcher
_timer.Interval = TimeSpan.FromSeconds(1);
_timer.Tick += (s, e) => UpdateTurbinesCo2();
}
public ObservableCollection<TurbinePin> GetTurbinePins(ICommand pinClickedCommand) {
_turbinePins = [
new() {
Turbine = new Turbine(_deviceLanguageService) {
Id = 1,
Name = "Estación Ciudadela Simón Bolívar",
Label = "Charge station",
Address = "Av. de las Américas, Guayaquil 090513, Ecuador",
Location = new Location(-2.151993, -79.886109),
InstalationDateTime = new DateTime(2024, 8, 2),
Images = ["charge_station.png", "wind_turbine.png"]
},
PinClickedCommand = pinClickedCommand
}
];
foreach (var pin in _turbinePins) {
CalculateAndSetValues(pin.Turbine!);
}
// Do not start the timer here
return _turbinePins;
}
// Start the timer explicitly
public void StartTimer() {
if (!isTimerRunning) {
_timer!.Start();
isTimerRunning = true;
}
}
// Method to handle updating CO2 every second
private void UpdateTurbinesCo2() {
foreach (var pin in _turbinePins) {
var turbine = pin.Turbine;
if (turbine != null) {
turbine.RemovedCo2Kilograms += turbine.RemovedCo2PerSecond; // Update CO2 every second
turbine.RemovedCo2Kilograms = RoundToDecimals(turbine.RemovedCo2Kilograms, 3);
}
}
}
and register a dispatcher as a dependency
Thanks for your sharing.
Best Regards,
Wenyan Zhang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.