Thursday, April 26, 2012

Timers and Ticks in Windows Phone 7

So I've come to the conclusion that this code

Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);


Sucks. The Timer Class gets garbage collected far too quickly.
I had added a timer.Start() and the function just debug.writeline to an int that counted up 30 times a second.
So after a few seconds it would count to about 213 or so, then it would stop. Nothing stopped it, i just disappeared even though the function wasn't told to stop. So I think it was garbage collected. And i found a few places that talked about the timer having to be called in a way that prevented it from being garbage collected. LAME!

However!

using System.Windows.Threading;
this line gives you a different way to do the exact same thing, and it's a lot more readable.

in the class define a nice variable
public class SomeClass
{

DispatcherTimer _timer;

public MainPage()
{
//this timer works way better.
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(30);
_timer.Tick += new EventHandler(Tick);
_timer.Start();
  InitializeComponent();  }
void Tick(object sender, EventArgs e)
{
//updating in a tick
}

}
that's it, that's all, nothing else needed.
The tick is called 30 times a second, and it never stops!
The other Timer() function gives me problems, this one doesn't I don't know why. But I am doing things on the windows phone, so that might have something to do with it.

Update 5pm
Moving into other things on the Phone, basically if you can access the MotionController vs the Gyro or the Accelerometer, you're better off. Things like getting Yaw Pitch and Roll or even Quaternion are way more useful than gyro and accelerator alone. Something I'd say you should do is just ignore phones that don't use motion controller. It's obvious, those phones will suck anyway.


No comments:

Post a Comment

rxokita's shared items