我希望每分钟运行一个从我的OnAppearing()开始的方法.我需要将此作为一项任务运行吗?

Ala*_*an2 3 c# timer xamarin xamarin.forms

这是我提出的代码.它似乎有用,但我担心它可能不是做我想做的好方法.我需要的是在OnAppearing发生时每分钟运行一个方法并使用OnDisappearing()停止它;

protected async override void OnAppearing()
{
   base.OnAppearing();
   BindingContext = vm;

   cts = new CancellationTokenSource();
   if (Settings.mode == MO.Practice)
   {
      if (!App.stopWatch.IsRunning) { App.stopWatch.Start(); }
            Device.StartTimer(new TimeSpan(0, 0, 5), () =>
      {
          if (App.stopWatch.IsRunning && App.stopWatch.Elapsed.Seconds >= 60)
          {
             // Here's the method I want to run. After it's finished
             // I call BeginInvoke .. to update info on the screen
             if (App.DB.ReducePoints() == true)
                Device.BeginInvokeOnMainThread(() =>
                {
                   vm.PifInfo = GetPifInfo();
                });
                App.stopWatch.Restart();
             }
             return true;
            });
        }
        await GetCards(cts.Token);
    }
}

protected override void OnDisappearing()
{
    Unsubscribe();
    cts.Cancel();
    if (App.stopWatch.IsRunning) { App.stopWatch.Stop(); }
    base.OnDisappearing();
}
Run Code Online (Sandbox Code Playgroud)

不是问题的一部分,但我也欢迎对代码的任何评论.谢谢

123*_*123 6

您可以通过返回正确的值Device.StartTimer,重复true,不重复false而不使用a 来更简单地执行此操作StopWatch.(来源指出,While the callback returns true, the timer will keep recurring.从源头看,该方法不需要Func<Task<bool>>它只需要Func<bool>回调,因此不需要使用Task.)

在课堂里

volatile bool run;
Run Code Online (Sandbox Code Playgroud)

在OnAppearing

run = true;
Device.StartTimer(new TimeSpan(0, 1, 0), () => {
if (run) { /*do what you want;*/ return true; }
else { return false; }
});
Run Code Online (Sandbox Code Playgroud)

在OnDisappearing

run = false;
Run Code Online (Sandbox Code Playgroud)

编辑 - 根据OP的要求

这是代码.我将离开原来的答案,以帮助其他需要此功能的人.

volatile bool run;

protected async override void OnAppearing()
{
   base.OnAppearing();
   BindingContext = vm;    
   cts = new CancellationTokenSource();
   if (Settings.mode == MO.Practice)
   {
        run = true;
        Device.StartTimer(new TimeSpan(0, 1, 0), () => 
        {
            if (run) 
            { 
                 if (App.DB.ReducePoints() == true)
                    Device.BeginInvokeOnMainThread(() =>
                    {
                       vm.PifInfo = GetPifInfo();
                    });
                 return true; 
            }
            else { return false; }
        });
        await GetCards(cts.Token);
    }
}

protected override void OnDisappearing()
{
    run = false;
    Unsubscribe();
    cts.Cancel();
    base.OnDisappearing();
}
Run Code Online (Sandbox Code Playgroud)