首页 > 解决方案 > 如何使用 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)
            }
      }

标签: c#xamarin

解决方案


以这种方式声明计时器使其作用于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它更加灵活。但是,范围界定问题仍然是相关的。


推荐阅读