Why isn't this working?

Hammy

Freshman
Joined
Jan 15, 2003
Messages
27
Location
Ontario, Canada
I have written this code, thinking it should produce an effect of the labels "flickering" random numbers 25 times for.2 seconds each time.

However, all it seems to do is cause the labels to go blank for .2 seconds x 25 times before finally diaplying their final result.

code...

Visual Basic:
Dim i As Integer
            For i = 1 To 50
                Label1.Text = CStr(Int(Rnd() * 10))
                Label2.Text = CStr(Int(Rnd() * 10))
                Label3.Text = CStr(Int(Rnd() * 10))
                System.Threading.Thread.Sleep(200)
            Next i

What am I doing wrong?

TIA
Hammy
 
Last edited by a moderator:
Thread.Sleep puts the thread to sleep, but no Windows messages are processed, such as painting. To see the results of each loop, you'll need to refresh the form before you sleep.

You could do a simple Application.DoEvents() which will process all messages including paint. You could call Me.Refresh() to refresh the form but not handle other messages (such as mouse clicks). Or you could call each control's Refresh method (Label1.Refresh()) to refresh each control.

-ner
 
The Application.DoEvents() that Divil suggested is the best way to go, but in VB6 I use Textboxes instead of labels (to stop the flickering) Though I haven't tested it out in .NET.
 
DoEvents will definitely work but has one possible drawback (or benefit) - it allows windows to process events. If you have a long running subroutine and you need to update labels, you should use Refresh. If you were to use DoEvents, the user could click a button (such as a Save button) more than once or even close the form.

If you have a long running subroutine and you *want* the user to be able to click a button (such as Cancel) then you should use DoEvents.

-nerseus
 
Back
Top