how to set timeout in VB.NET RRS feed

  • Question




    let say if I have a function called abc(input_val) with return code integer, and I would like to set timeout for this function, so that if it cannot complete within the time limit, then kill it and proceed next, how should I implement it?




    step 1

    method.timeout = 5000 ' 5000 mil sec

    If (method.run(abc())) =0 then

    step 2



    end if


    so that if abc() can't complete in 5000 mil sec, then proceed step 2, if it finish before 5000 mil sec, then process step 3


    Is it possible?? thanks.

    Thursday, October 25, 2007 11:35 AM


  • Hi MKHA,

    The basic idea is to use the ThreadPool.QueueUserWorkItem Method to execute the worker function and use an vent and the WaitHandle.WaitAll Method to monitor the worker function. Please check out the following code example:

    Code Block

    Private Result As Object = Nothing 'Store the worked result of abc()
    Private Sub Worker(ByVal state As Object)
        Dim are As AutoResetEvent = DirectCast(state, AutoResetEvent)
        ' do anything you want here:
        Dim result As Integer = 0
        'result = abc(input_val);
        SyncLock Me.Result
            Me.Result = result
        End SyncLock
    End Sub
    Private Sub method()

        Const TimeOut As Int32 = 5000
        Dim [handles] As WaitHandle() = New WaitHandle() {New AutoResetEvent(False)}
        ThreadPool.QueueUserWorkItem(New WaitCallback(Worker), [handles](0))
        Dim finished As Boolean = WaitHandle.WaitAll([handles], TimeOut, True)
        'ThreadPool.RegisterWaitForSingleObject ()
        If finished Then
                ' step 2
            MessageBox.Show("Worker function finished sucessfully, go to Step2")
                ' step 3
            MessageBox.Show([String].Format("Worker function time out({0})!, go to Step3", TimeOut))
        End If
    End Function



    If the worker function finished in time represented by TimeOut, the return value of WaitHandle.WaitAll will be true, false else.

    Hope this helps!




    Monday, October 29, 2007 8:31 AM