Link to home
Start Free TrialLog in
Avatar of rishaan
rishaan

asked on

Wait fn/sleep/delay

I need to create a delay of few seconds in my code.
Is there any efficient function to do that.
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Here are two different ways to create a delay.  The first makes the app delay in one line but then the app becomes unresponsive during that interval.  Hit the button and then try moving the form.  It will not respond until the interval is over.  Then second approach gives you a delay while keeping the app responsive.  Another alternative would be to use a Timer and boolean flag:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button1.Enabled = False

        System.Threading.Thread.Sleep(5000) ' five seconds

        Button1.Enabled = True
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Button2.Enabled = False

        Dim targetTime As DateTime = DateTime.Now().AddSeconds(5)
        Dim ts As TimeSpan
        Do
            Application.DoEvents() ' keep application responsive
            System.Threading.Thread.Sleep(50) ' very small delay to reduce CPU Usage
            ts = targetTime.Subtract(DateTime.Now)
        Loop While ts.TotalSeconds > 0

        Button2.Enabled = True
    End Sub
Avatar of rishaan
rishaan

ASKER

My application(service) is actually calling some other app and it has to wait till the other app takes on all the locks
So which one is good in my case??
Will thread.sleep etc cause any problem...I havent used threads...
>> it has to wait till the other app takes on all the locks

How do you know when this other app is done?  Do you need to wait for it to close?
Avatar of rishaan

ASKER

no. I don't have to wait till it is done. But I have to give a delay to make sure the locks released by my app are taken by the other app.
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial