Issue
I am sorry if this has been asked. I couldn't find the answer to this question specifically and am stuck. I am learning about timers right now. I am a VBA programmer and dabble in C#.
I am trying to write a cross-platform app right now and am having trouble with my myTimer.Elapsed event from updating the label as it is supposed to do.
I have read the timers chapter in C# Notes for Professionals from goalkicker.com and have tried to replicate their countdown timer. I have also read the Microsoft API for Timer.Elapsed Event. Neither have given me an explicit answer as to where I am going wrong. Google hasn't been too kind, either, as I might be querying incorrectly.
I have tried stopping the timer, just allowing the method to run, writing to the label directly within my Elapsed method and updating the label in a separate method (as seen in the code).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading;
using System.Timers;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Essentials;
using Plugin.Geolocator;
namespace LocationServices
{
public partial class MainPage : ContentPage
{
public int timeLeft = 3;
public Timer myTimer = new Timer();
SensorSpeed speed = SensorSpeed.UI; //ignore
public MainPage()
{
InitializeComponent();
cmdGetLocation.Clicked += GetLocation; //ignore
cmdStartTimer.Clicked += StartTimer;
Accelerometer.ReadingChanged += MainPage_ReadingChanged; //ignore
InitializeTimer();
}
private void UpdateTimeLeftLabel(string NumberToDisplay)
{
txtTimeRemaining.Text = "Time left: " + NumberToDisplay;
}
private void InitializeTimer()
{
myTimer.Interval = 1000;
myTimer.Enabled = true;
myTimer.Elapsed += MyTimer_Elapsed;
UpdateTimeLeftLabel(timeLeft.ToString()); //working just fine
}
private void MyTimer_Elapsed(object sender, ElapsedEventArgs e)
{
myTimer.Stop();
UpdateTimeLeftLabel(timeLeft.ToString()); //this one is not working.
if (timeLeft <= 0)
{
myTimer.Dispose();
}
else
{
timeLeft -= 1;
myTimer.Start();
}
}
private void StartTimer(object sender, EventArgs e)
{
myTimer.Start();
}
}
}
My timer event is firing as breakpoints are being hit as expected. The timeLeft variable is being adjusted as has been verified in the immediate window. It's just the label that is not getting updated.
Solution
use BeginInvokeOnMainThread
to force your UI code to run on the UI thread
private void UpdateTimeLeftLabel(string NumberToDisplay)
{
Device.BeginInvokeOnMainThread( () => {
txtTimeRemaining.Text = "Time left: " + NumberToDisplay;
});
}
Answered By - Jason Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.