有没有办法取消 Xamarin 中正在运行的计时器?

Ala*_*an2 0 xamarin xamarin.forms

我的代码中有这个计时器:

            Device.StartTimer(TimeSpan.FromSeconds(100), () =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    if (detailGrid.IsVisible == true)
                    {
                        getRandomPhase();
                    }
                });
                return false;
            });
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以(通过手势)取消计时器的运行或以某种方式中止计时器?

小智 5

计时器回调的返回值是一个布尔值,用于确定计时器是否应该继续运行或停止。您可以使用私有变量来跟踪计时器是否应继续运行并从回调中返回它。

请检查此样本

private bool _isTimerStart = true;  

           private void StartTimers()  
           {  
               try  
               {  
                   Device.StartTimer(new TimeSpan(0, 0, 1), () =>  
                   {  
                      // do some code here

                       return _isTimerStart;  
                   });  
               }  
               catch {}  
           }      private void BtnStart_OnClicked(object sender, EventArgs e)  
           {  
               _isTimerStart = true;  
               StartTimers();  
           }  

           private void BtnStop_OnClicked(object sender, EventArgs e)  
           {  
               _isTimerStart = false;  
           }
Run Code Online (Sandbox Code Playgroud)

此代码取自以下博客文章,其中显示了更详细的示例:http://www.c-sharpcorner.com/article/quick-start-tutorial-creating-universal-apps-via-xamarin-device-classcont/