c# - 如何使用 Xamarin 按钮的 Click 事件停止 C# 计时器?
问题描述
我有一个工作计时器方法,它调用 API 函数以每 3 秒获取一次新的股票价格数据。该方法运行良好,并且每 3 秒不断更新我的 Xamarin 表单中的数据。此方法称为“RefreshData()”,我从 MainPage() 类中调用它。
当我的 Xamarin Button 对象调用 Click 处理程序(“Handle_Clicked”)时,我一直在尝试找到正确停止计时器的语法。
我尝试过 myTimer.Change 方法、myTimer.Dispose 方法和 Timeout.Infinite 方法。它们看起来都很简单,但我的语法一定是错误的,因为这些方法要么在 Visual Studio 中无法识别为红色下划线所示,要么会产生其他错误。
我正在寻找一些关于获得正确、有效的语法以关闭此计时器和/或可能再次将其重新打开的指导。
这是我在所有其他方面都有效的代码片段......
谢谢你的帮助 :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xamarin.Forms;
using System.Timers;
namespace MyTimerTest
{
[System.ComponentModel.DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
LoadData(); // Loads the initial data when the page loads
RefreshData(); // Calls the timer method which refreshes the data
}
void RefreshData() // Sets the timer to call the UpdateData method which calls the LoadData method to get fresh data and update the UI with it
{
int seconds = 3 * 1000;
var myTimer = new System.Threading.Timer(UpdateData, null, 0, seconds);
}
public void UpdateData(object o)
{
LoadData(); // <-- call for JSON API data, works fine and updates accordingly to the timer
}
void Handle_Clicked(object sender, EventArgs e)
{
myTimer.Dispose(); // <-- Error: myTimer doesn't exist in current context
// myTimer.Change(Timeout.Infinite, Timeout.Infinite)
}
}
解决方案
以这种方式声明计时器使其作用于LoadData
方法
void RefreshData() // Sets the timer to call the UpdateData method which calls the LoadData method to get fresh data and update the UI with it
{
int seconds = 3 * 1000;
var myTimer = new System.Threading.Timer(UpdateData, null, 0, seconds);
}
相反,在类级别(特定方法之外)声明它,以便在类中的任何地方都可以访问它
System.Threading.Timer myTimer;
scope
是一个通用的 C# 概念(实际上是一个通用的编程概念),并不专门与 Xamarin 相关联
此外,正如@enigmativity 所提到的,System.Timers.Timer
它更加灵活。但是,范围界定问题仍然是相关的。
推荐阅读
- reactjs - React Formik onSubmit Async 调用了两次
- javascript - 递归语句,遍历嵌套对象/数组 - 但是它怎么知道这样做呢?(JS算法)
- docker - 这个命令有什么问题 - docker volume 命令
- javascript - 被 CORS 政策阻止的 Firebase 函数 api
- android - 这些声明之间有什么区别 - Kotlin
- php - PhpStorm 本地终端
- mysql - fk 和 pk 存在问题,它们在同一个表中并且相关
- c - 有没有办法从带有其他信息的文本文件中读取全名?
- html - 设置后备维度
- math - 在乳胶中,如何键入一个中间带点的等号数学符号?