Simple, non-blocking way to sleep?

Gulbahar picture Gulbahar · Feb 10, 2010 · Viewed 37.5k times · Source

I googled for this and read some threads here, but I haven't found a simple way to have a VB.Net application sleep for a little while and still keep the application responsive:

Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Threading.Thread

[...]

''#How to keep screen frop freezing?
While True
  ListBox1.Items.Clear()

  ListBox1.Items.Add("blah")

  ''#Not much difference
  ListBox1.Refresh()

  ''#Wait 1mn
  Sleep(60000)
End While

Is there really no simple, non-blocking solution to have a VB.Net application wait for a few seconds?

Thank you.

Answer

user408874 picture user408874 · Aug 2, 2010
Public Sub ResponsiveSleep(ByRef iMilliSeconds As Integer)
    Dim i As Integer, iHalfSeconds As Integer = iMilliSeconds / 500
    For i = 1 To iHalfSeconds
        Threading.Thread.Sleep(500) : Application.DoEvents()
    Next i
End Sub

Call ResponsiveSleep to pause a particular piece of code whilst keeping the application fairly responsive. To make the application more responsive iHalfSeconds could be modified to tenths or hundredths of a second