首页 > 解决方案 > 我想从我的 OnAppearing() 开始每分钟运行一个方法。我需要将其作为任务运行吗?

问题描述

这是我想出的代码。它似乎有效,但我担心这可能不是做我想做的事的好方法。我需要的是在 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();
}

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

标签: c#xamarinxamarin.formstimer

解决方案


Device.StartTimer您可以通过从、 重复true、 不重复false和不使用返回正确值来更简单地执行此操作StopWatch。(来源声明,While the callback returns true, the timer will keep recurring.正如您从源代码中看到的那样,该方法不需要 aFunc<Task<bool>>它只需要一个Func<bool>回调,因此不需要使用 a Task。)

在课堂里

volatile bool run;

在出现

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

在 OnDisappearing

run = false;

编辑 - 根据 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();
}

推荐阅读