When I display the page, I need to make requests every one minute to update the data in the table that is presented. I don't know where to add this timer logic, since all controller lifecycle methods should end at the appropriate time - I guess?
Where should I put the timer?
1 Answers
Answers 1
Since you are saying you need to make request every one minute after you display the page, good solution is to start the timer in ViewWillAppear()
method and stop it in ViewWillDisappear()
- it will be running just when the ViewController is visible in foreground. Unbinding the OnTimedEvent
is important to avoid memory leak.
Is that what you need or do you have some more specific requirement?
Sample code:
class MyViewController : UIViewController { public MyViewController(IntPtr handle) : base(handle) { } private Timer timer; private bool timerEventBinded; public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); if (timer == null) { timer = new Timer(); timer.Enabled = true; timer.Interval = 60000; } if (!timerEventBinded) { timer.Elapsed += OnTimedEvent; timerEventBinded = true; } timer.Start(); } public override void ViewWillDisappear(bool animated) { if (timer != null) { timer.Stop(); if (timerEventBinded) { timer.Elapsed -= OnTimedEvent; timerEventBinded = false; } timer = null; } base.ViewWillDisappear(animated); } private void OnTimedEvent(Object src, ElapsedEventArgs e) { //do your stuff } }
0 comments:
Post a Comment