gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:02:33 26 4
gpt4 key购买 nike

当我使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com