Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple, non-blocking way to sleep?

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.

like image 784
Gulbahar Avatar asked Feb 10 '10 14:02

Gulbahar


People also ask

Why thread sleep is not good?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

What can we use instead of thread sleep?

You could also do throws InterruptedException in method definition to avoid try/catch block , or use TimeUnit. MILLISECONDS. sleep() instead.

What's the difference between sleep () and wait ()?

Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context. There is no need to call sleep() from Synchronized context.

Is sleep a blocking call?

Yes, sleep is blocking.


1 Answers

How about this simple piece of code - :)

Private Async Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        MsgBox("This msgbox is shown immidiatly. click OK and hover mouse over other controls to see if UI is freezed")
        Await Task.Delay(5000)
        MsgBox("see? UI did'nt freez :). Notice the keyword 'Async' between Private and Sub")
    End Sub

Use Async on declared sub and then put Await Task.Delay(milliseconds) instead of Thread.Sleep(milliseconds)

like image 74
Manoj Bhakar PCM Avatar answered Oct 06 '22 14:10

Manoj Bhakar PCM