Reputation: 883
Im currently creating a GUI application framework as part of Ionite Framework. Which i will use for my school final project, my question is:
Im using thread for maintaining the animation,
ParameterizedThreadStart iv = new ParameterizedThreadStart(o => {
this.Size = (Size)o;
});
new Thread(()=>{
float stepWidth = (targetWidth-currentWidth)/transition;
float baseWidth = currentWidth;
int tick=transition;
while(tick-- > 0){
baseWidth+=stepWidth;
Invoke(iv,new Size(baseWidth,this.Height));
Thread.Sleep(1);
}
}).Start();
Assuming that the this operator is a Control object. When i use background on my control object, its longer than its expected.
Whats wrong with my code/method? Thanks
Upvotes: 0
Views: 429
Reputation: 941505
Thread.Sleep(1);
That doesn't do what you hope it does. The Sleep() method can only sleep for intervals that are equal or an integer multiple of the clock tick resolution of the operating system. Which, by default, ticks 64 times per second. Or 15.625 milliseconds. So your animation in effect runs 16 times slower than you think.
This is technically something you can fix by pinvoking timeBeginPeriod(1). But you shouldn't, 16 milliseconds is plenty good enough to make any animation look smooth to the human eye. Simply make your stepWidth variable 16 times bigger. Assuming that otherwise your UI thread can keep up with the required painting rating.
Next step is to recognize that using a thread is useless, it can still only go as fast as you can Invoke(). Which requires the UI thread to be responsive enough. So use a plain synchronous Timer instead for the exact same outcome, minus the overhead of a thread.
Upvotes: 2