0

I want to create an animation moving object .. in order to move this object i need to update the coordinates x and y or one of them, the problem is the object is jamb to the final position with no smooth moving animation as suppose to... I used thread sleep but doesn't just make the code freeze then the object jamb.. Here is the not working part of the code

public void t_Tick(object sender, EventArgs e)
{
    if (flag)
    {
        for (int i = 0; i < 100; i = i + 1)
        {
            x-position = x-position + 3;
            Invalidate();
            Thread.Sleep(5000);//instead of stop for 5 second and continue the loop is stop 5 second and go to i=100 the final value in the loop
        }
        flag = false;
    }
}
DAXaholic
  • 33,312
  • 6
  • 76
  • 74

2 Answers2

1

Ask yourself the question:

What do I want my code to do once every t.Interval millisecond?

The answer is

Move the Control once.

So move it only once in the t_Tick method.

You think my answer is wrong because there is no for loop, but there is one included in the timer. In the Timer class, there is some code that does domsething like this:

while (true) {
  form1.t_Tick(...);
  Thread.Sleep(Interval);
}

NOTE: this is not real code found in the Timer code, it's just meant to explain the concept behind timers.

So what does your current code do?

It moves exactly how you would like it to do, but Thread.Sleep() blocks the thread you are on and nothing else is done, just like if you had a debug breakpoint on that line of code. Therefore, Invalidate() may be called, but the code that repaints your form isn't called until you leave the for loop (when it has moved completely).

SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
0

Try Refresh() instead of Invalidate() to force drawing the control immediately. By calling Invalidate(), you essentially just tell the control that some of its parts (or everything) needs to be repainted, but not to do it right now. Please note that this is not a good way of doing it, as calling Thread.Sleep causes your UI thread to be blocked.

See here for a similar question and its answers where a more canonical way is used.

Community
  • 1
  • 1
DAXaholic
  • 33,312
  • 6
  • 76
  • 74