我正在使用 Monotouch 为 iPad 开发一个基于调查的应用程序,并且我正在尝试实现一个计时器,如果有人回答的时间太长 (_survey.Timeout),该计时器会将调查返回到第一个问题。
我在 View Controller 中使用以下代码,它在第一次被触发时工作正常,但它继续循环 - 所以问题是,当新 View Controller 出现时,我如何停止线程并正确处理计时器被推送,以便它在新 View 中有效地从 0 秒重新启动。
/* ViewDidLoad */
if (_survey.CurrentQuestion != 1)
{
var thread = new Thread(StartTimer as ThreadStart);
thread.Start();
}
/* ThreadStart */
void StartTimer()
{
using (var pool = new NSAutoreleasePool())
{
NSTimer.CreateScheduledTimer(_survey.Timeout, delegate {
_survey.CurrentQuestion = 1;
_survey.Responses.Clear();
QuestionController qvc = new QuestionController(_survey);
this.NavigationController.PushViewController(qvc, false);
});
NSRunLoop.Current.Run();
}
}
我知道这可能是一件非常简单的事情,但请让我摆脱痛苦!
请您参考如下方法:
CreateScheduledTimer 返回一个 NSTimer。对该对象调用 Invalidate:
NSTimer timer;
void StartTimer()
{
using (var pool = new NSAutoreleasePool())
{
timer = NSTimer.CreateScheduledTimer(_survey.Timeout, delegate {
_survey.CurrentQuestion = 1;
_survey.Responses.Clear();
QuestionController qvc = new QuestionController(_survey);
this.NavigationController.PushViewController(qvc, false);
});
NSRunLoop.Current.Run();
}
}
void StopTimer ()
{
timer.Invalidate ();
timer.Dispose ();
timer = null;
}
