0

I am using this code in a lot of places in my application and I know an alternative is using timers but that means I would have to add about 20 of them.. the issue with this is that if this is running and I close the app it hangs.. is there an alternative to use a function like this but with one timer instead?

Public Sub Delay_App(ByVal DelayInMilliseconds As Integer)
    Dim ts As TimeSpan
    Dim targetTime As DateTime = DateTime.Now.AddMilliseconds(DelayInMilliseconds)
    Do
        ts = targetTime.Subtract(DateTime.Now) 
        Application.DoEvents() 
        System.Threading.Thread.Sleep(50) 
    Loop While (ts.TotalSeconds > 0) AndAlso Application.OpenForms.Count > 0
End Sub
XK8ER
  • 770
  • 1
  • 10
  • 25

1 Answers1

2

As already mentioned this is not really a good design if you have to have to be doing this in a lot of places. But without knowing what you want to achieve, I better solution can't really be offered. In the meantime I will give you a solution to your problem:

Add a global variable that signifies that your application is closing.

Public AppClosing as Boolean

Set this to True when your application is closing:

Public Event Form_Closing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    AppClosing = True
End Sub

Then in your delay just check the status of this flag:

Public Sub Delay_App(ByVal DelayInMilliseconds As Integer)
    Dim ts As TimeSpan
    Dim targetTime As DateTime = DateTime.Now.AddMilliseconds(DelayInMilliseconds)
    Do
        ts = targetTime.Subtract(DateTime.Now) 
        Application.DoEvents() 
        For i as Integer = 1 to 50
             System.Threading.Thread.Sleep(1)
             If AppClosing Then Exit Sub 'Application is closing so don't wait for the time
        Next
    Loop While (ts.TotalSeconds > 0) AndAlso Application.OpenForms.Count > 0
End Sub
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143