c# - How can I cancel from Device.StartTimer? -
when use system.threading.timer can stop timer , start again:
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); } }
what best way stop device.starttimer , start again?
i guessing referring device.starttime in xamarinforms. way stop or continue recurring task determined second argument returns:
// run task in 2 minutes device.starttimer(timespan.fromminutes(2), () => { if (needstorecur) { // returning true fire task again in 2 minutes. return true; } // no longer need recur. stops firing task return false; });
if want temporarily stop timer, , fire again after time, have call device.starttimer
again. nice wrap own class can use private member determine if continuous task still running. this:
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) // 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 recur. stop return isrunning = false; } } }
Comments
Post a Comment