jvcoach23
jvcoach23

Reputation: 3037

dynamic timer in vb.net

I've got a vb app in .Net 4 that i'm working on. The app fires up dynamic threads to run some jobs. Each thread runs a certain job and within that thread, it performs a infinate loop. It needs to be this way, i can't have the thread and then begin again...

anyway.. i was using threading.thread.sleep in the loop to have the loop pause for a bit before running again. It seems that this is not a good way to go and not recommended. So i thought perhaps i could use a dynamic timer or something else to have the thread wait for say 30 seconds before running again. i was hoping someone could give me some direction and example code.

thanks shannon

~~~~~~~~~~edit hey.. i figured out the problem and no.. it wasn't the sleep in the background thread.... it was a sleep i didn't realize i put in in the UI thread.. I started commented out everything and started adding in 1 by 1 and found it. Sorry PEBKAM error...

Thanks for the input

Upvotes: 0

Views: 1483

Answers (1)

Amen Ayach
Amen Ayach

Reputation: 4348

Use the following class to do the delay, i developed with same concept of javascript:settimeout :

Public Class JSsetTimeout

    Public res As Object = Nothing
    Dim WithEvents tm As Timer = Nothing
    Dim _MethodName As String
    Dim _args() As Object
    Dim _ClassInstacne As Object = Nothing

    Public Shared Sub SetTimeout(ByVal ClassInstacne As Object, ByVal obj As String, ByVal TimeSpan As Integer, ByVal ParamArray args() As Object)
        Dim jssto As New JSsetTimeout(ClassInstacne, obj, TimeSpan, args)
    End Sub

    Public Sub New(ByVal ClassInstacne As Object, ByVal obj As String, ByVal TimeSpan As Integer, ByVal ParamArray args() As Object)
        If obj IsNot Nothing Then
            _MethodName = obj
            _args = args
            _ClassInstacne = ClassInstacne
            tm = New Timer With {.Interval = TimeSpan, .Enabled = False}
            AddHandler tm.Tick, AddressOf tm_Tick
            tm.Start()
        End If
    End Sub

    Private Sub tm_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tm.Tick
        tm.Stop()
        RemoveHandler tm.Tick, AddressOf tm_Tick
        If Not String.IsNullOrEmpty(_MethodName) AndAlso _ClassInstacne IsNot Nothing Then
            res = CallByName(_ClassInstacne, _MethodName, CallType.Method, _args)
        Else
            res = Nothing
        End If
    End Sub
End Class

Usage

JSsetTimeout.SetTimeout(ClassContainingMethod, "MethodName", 30000, OptionalParameters)

Upvotes: 1

Related Questions