如果有人问过这个问题,我很抱歉。我找不到这个问题的具体答案并且被卡住了。我现在正在学习计时器。我是一名 VBA 程序员,并涉足 C#。
我现在正在尝试编写一个跨平台应用程序,并且我的 myTimer.Elapsed 事件无法按预期更新标签。
我已阅读来自goalkicker.com 的C# 专业人士注释中的计时器章节,并尝试复制他们的倒计时计时器。我还阅读了 Microsoft API for Timer.Elapsed Event。两者都没有给我一个明确的答案,说明我哪里出错了。谷歌也不太友好,因为我可能查询不正确。
我尝试停止计时器,只允许该方法运行,直接在我的 Elapsed 方法中写入标签并在单独的方法中更新标签(如代码中所示)。
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();
}
}
}
我的计时器事件正在触发,因为断点按预期被击中。正在调整 timeLeft 变量,已在即时窗口中验证。只是标签没有更新。