Search code examples
vb.nettextbox

Strange interaction between thread.sleep and textboxes/labels


I am writing a VB user interface for an Arduino based instrument and while the instrument is doing something I wanted VB to wait. To show what's happening at the time I was going to change a label or a textbox to update the current state of the instrument. However, when I combine a textbox1.text="" with a thread.sleep(n) command, VB will execute the sleep function first before updating the textbox.

Imports System.Threading

Public Class Form

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TextBox1.Text = "Hello World!"
        Thread.Sleep(3000)
    End Sub

End Class

The code will wait 3 sec and THEN write "Hello World" Any idea how I can force the update of the textbox or label without executing the sleep command first?


Solution

  • This is the way Windows works. The thread that updates all the UI is the same thread that runs the button click handler. By making it sleep for 3 seconds you stop it doing its job of updating the UI. You make the change to the label but it won't take effect until the thread exits your click handler method and goes back to its normal job of drawing the user interface, processing clicks etc

    Use

    Await Task.Delay(3000) 
    

    Instead, and mark your click handler method as Async

    In a nutshell Async/Await allows the thread to pause the current method (your click) and go back to what it was doing, then when the delay expires, the thread will be brought back to your method and continue where it left off (after the await line) with all the variables intact etc. Use this method to wait for long running things (like file IO/downloads) without freezing your UI