Cobold
Cobold

Reputation: 2613

For each loop doesn't sleep

I have a For..Each loop which loops trough all grid's rectangles and changes the fill of them randomly. I change the fill with a color animation. Here's my code:

        Dim rand as new random
        Dim changeColor As New Animation.ColorAnimation

        changeColor.Duration = TimeSpan.FromSeconds(0.5)

        For Each r As Rectangle In Grid.Children
            changeColor.From = ColorConverter.ConvertFromString(r.Fill.ToString)            
            Dim i As Integer = rand.Next(0, 2)
            Select Case i
                Case 0
                    changeColor.To = Colors.White
                Case 1
                    changeColor.To = Colors.Gray
            End Select
            Animation.Storyboard.SetTarget(changeColor, r)
            Animation.Storyboard.SetTargetProperty(changeColor, New PropertyPath("Fill.Color"))
            Dim sb As New Animation.Storyboard
            sb.Children.Add(changeColor)

            sb.Begin()
            System.Threading.Thread.Sleep(0.5)
        Next

The problem is that the loop doesn't sleep. I want to trigger the animation, then wait until the rectangle fill is changed and then continue with the rest, but it seems that all of the rectangles fill are changed in the same time. So what I'm doing wrong?

Upvotes: 1

Views: 436

Answers (3)

Stephen Wrighton
Stephen Wrighton

Reputation: 37839

Thread.Sleep takes in MILLISECONDS as the time. So you're saying that you want this to sleep for 0.5 milliseconds (or 0.00005 seconds).

Which may or may not be enough to finish the task.

Then, there's also the possibility that you're running in the same thread as the UI. If that's the case, then unless you invalidate the visual, the screen won't refresh until you finish processing.

Upvotes: 0

brunnerh
brunnerh

Reputation: 184607

You sleep the UI thread, so both the loop and all rendering is halted. You could try a method like this one i wrote for another question.

Edit: Also change the time as pointed out by Michael Holdshteyn.

Upvotes: 2

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74390

Replace:

System.Threading.Thread.Sleep(0.5)

With:

System.Threading.Thread.Sleep(500)

The sleep value is an integer and is in Milliseconds. When you do Sleep(0.5) all you're getting is a context switch.

Upvotes: 0

Related Questions