c# - 如何从 Device.StartTimer 取消?

标签 c# android timer xamarin

当我使用 System.Threading.Timer 时,我可以停止我的计时器并重新启动它:

protected override void OnScrollChanged(int l, int t, int oldl, int oldt)
{
    if (timer == null)
    {
        System.Threading.TimerCallback tcb = OnScrollFinished;
        timer = new System.Threading.Timer(tcb, null, 700, System.Threading.Timeout.Infinite);
    }
    else
    {
        timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
        timer.Change(700, System.Threading.Timeout.Infinite);
    }
}

停止 Device.StartTimer 并重新启动它的最佳方法是什么?

最佳答案

我猜您指的是 XamarinForms 中的 Device.StartTime。停止或继续重复任务的方式由第二个参数返回的内容决定:

// run task in 2 minutes
Device.StartTimer(TimeSpan.FromMinutes(2), () =>
{
    if (needsToRecur)
    {
        // returning true will fire task again in 2 minutes.
        return true;
    }

    // No longer need to recur. Stops firing task
    return false; 
});

如果你想暂时停止这个计时器,然后在一段时间后再次启动它,你将不得不再次调用 Device.StartTimer。最好将它包装到它自己的类中,您可以在其中使用私有(private)成员来确定连续任务是否仍在运行。像这样:

public class DeviceTimer
{
  readonly Action _Task;
  readonly List<TaskWrapper> _Tasks = new List<TaskWrapper>();
  readonly TimeSpan _Interval;
  public bool IsRecurring { get; }
  public bool IsRunning => _Tasks.Any(t => t.IsRunning);

  public DeviceTimer(Action task, TimeSpan interval, 
    bool isRecurring = false, bool start = false)
  {
    _Task = task;
    _interval = interval;
    IsRecurring = isRecurring;
    if (start)
      Start();
  }

  public void Restart()
  {
    Stop();
    Start();
  }

  public void Start()
  {
    if (IsRunning)
      // Already Running
      return;

    var wrapper = new TaskWrapper(_Task, IsRecurring, true);
    _Tasks.Add(wrapper);

    Device.StartTimer(_interval, wrapper.RunTask);
  }

  public void Stop()
  {
    foreach (var task in _Tasks)
      task.IsRunning = false;
    _Tasks.Clear();
  }


  class TaskWrapper
  {
    public bool IsRunning { get; set; }
    bool _IsRecurring;
    Action _Task;
    public TaskWrapper(Action task, bool isRecurring, bool isRunning)
    {
      _Task = task;
      _IsRecurring = isRecurring;
      IsRunning = isRunning;
    }

    public bool RunTask()
    {
      if (IsRunning)
      {
        _Task();
        if (_IsRecurring)
          return true;
      }

      // No longer need to recur. Stop
      return IsRunning = false;
    }
  }         
}

关于c# - 如何从 Device.StartTimer 取消?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32304766/

相关文章:

c# - C# 编译器是否删除了封装 debug.writeline 的 if

c# - 在 C# 中的 List<> 中避免重复的快速方法

android - 包括抽屉导航底部的行

java - 在 Libgdx 中创建另一个纹理时,我应该调用 dispose() 纹理吗?

android - TelephonyManager 类型的相对速度?

c# - 使用 WHERE 条件返回文件列表的最短方法

c# - System.UnauthorizedAccessException 调用 UserPrincipal.SetPassword

c++ - 如何重启 boost::timer::cpu_timer?

ios - Xcode 无法识别 Timer() - Swift 3

swift - 我需要一个可靠的 Swift 3 秒表