Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem using NSTimer in MonoTouch .NET thread

I have a problem using an NSTimer in MonoTouch. To start with I ran an NSTimer in my main thread, which worked. However, I've moved the timer to a separate thread, and I never get a callback. I'm guessing this is because my .NET style thread isn't a run loop - but I'm quite new to MonoTouch/iOS so not sure.

I've extracted the code to a test project and had the same issue. This is the code that fails:

var thread=new Thread(StartTimer as ThreadStart);
thread.Start();

[Export("StartTimer")]
void StartTimer()
{
    using(var pool = new NSAutoreleasePool())
    {
         timer=NSTimer.CreateRepeatingScheduledTimer(2,delegate { Twitch() } );
         Thread.Sleep(1000000);    // do I have to yield here somehow?
    }
}

void Twitch()
{
    Debug.WriteLine("Twitch");
}
like image 294
vlad259 Avatar asked Jan 19 '11 16:01

vlad259


1 Answers

You are correct, the issue it never fires is that you've put the thread to sleep and never started a runloop. Try:

NSRunLoop.Current.Run ();

Instead of your

Thread.Sleep (1000000);
like image 89
Geoff Norton Avatar answered Sep 17 '22 00:09

Geoff Norton