Search code examples
vb.netlabelsleep

Typing one letter at a time with delays to a label in VB.NET; how to make program not appear to freeze?


I am trying to use a method in VB.NET that types a message one letter at a time into a label's text (in Windows Form App) and then pauses to let the user read it after it is done.

The interval between typing each letter is 20 ms, and the delay at the end is 750 ms.

The code that I tried does type the message correctly, but it is called multiple times during code execution before the user must input again, and the program appears to freeze for several seconds before the user is able to input. The goal is for the message typing to be visible to the user in the code execution before input is available again.

How do I make it visible to the user?

Here is the method called to output the message in the code:

            Do Until lblText.Text = Response
            If LettersTyped = 0 Then
                lblText.Text = ""
            End If
            lblText.Text = lblText.Text & Mid(Response, (LettersTyped + 1), 1)
            LettersTyped += 1
            System.Threading.Thread.Sleep(20)
            '20 ms delay before writing so it appears to type out to the user
            Loop
        LettersTyped = 0
        System.Threading.Thread.Sleep(750)
        'Pause code execution for 750 ms before returning to method that called this

Where Response is a String that stores the message to type out, lblText is a Label that displays the response, and LettersTyped is an integer that tracks the letters typed out

This code does succeed in typing, but the form just appears frozen to the user for a while instead of showing the user the messages being typed out.


Solution

  • use Await Task.Delay() instead of System.Threading.Thread.Sleep() to prevent blocking the UI thread.

    note you will also have to mark your method as Async and possibly Await any calls to it