setTimeout equivalent in VB.NET
Sometimes I just need a function which will execute something after a specified period of time. In JavaScript, this is extremely easy using setTiimeout. I miss this in VB.NET, so I implemented my own function to do this :)
Code:
Module Timeout
Friend timers As New Dictionary(Of Integer, Timer)
Friend threads As New Dictionary(Of Integer, [Delegate])
Friend forms As New Dictionary(Of Integer, Form)
Friend paramarrays As New Dictionary(Of Integer, Object())
Sub setTimeout(ByRef form As Form, ByVal method As [Delegate], ByVal time As Integer, ByVal ParamArray args As Object())
Dim v = (New Random).Next(0, Integer.MaxValue)
Dim t As New Timer
t.Enabled = True
t.Interval = time
t.Tag = v
AddHandler t.Tick, AddressOf continuetimer
timers.Add(v, t)
threads.Add(v, method)
forms.Add(v, form)
paramarrays.Add(v, args)
End Sub
Sub continuetimer(ByVal sender As Timer, ByVal e As EventArgs)
Dim ct As New EventHandler(AddressOf continuetimer)
RemoveHandler sender.Tick, ct
Dim v = sender.Tag
sender.Enabled = False
timers.Remove(v)
forms(v).Invoke(threads(v), paramarrays(v))
threads(v) = Nothing
threads.Remove(v)
sender.Dispose()
End Sub
End Module
Use (it will show Hello world! in 3 seconds:
Code:
Sub example(text)
MsgBox(text)
End Sub
setTimeout(Me, New Action(AddressOf example), 3000, "Hello world!")