Force a subroutine to close

Hi Experts,

The code below uses a timer to start a subroutine every ten minutes to scrape some information from a web page. Sometimes the web page being scraped does not load and the subroutine hangs. When the timer ticks again the subroutine is started again and an attempt to scrape the page is started again.

If the subroutine hangs how do I  force it to terminate so when the timer ticks so a new instance of the subroutine is started?

    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick


    End Sub

Open in new window

Who is Participating?
Bob LearnedConnect With a Mentor Commented:
You should look into asynchronous calls, with cancellation, as shown here:

Cancellation in Managed Threads

Shared Sub CancelWithThreadPoolMiniSnippet()

    'Thread 1: The Requestor 
    ' Create the token source. 
    Dim cts As New CancellationTokenSource()

    ' Pass the token to the cancelable operation.
    ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf DoSomeWork), cts.Token)

    ' Request cancellation by setting a flag on the token.
    ' end block 
End Sub 

'Thread 2: The Listener 
Shared Sub DoSomeWork(ByVal obj As Object)

    Dim token As CancellationToken = CType(obj, CancellationToken)
    For i As Integer = 0 To 1000000

        ' Simulating work.

        If token.IsCancellationRequested Then 

            ' Perform cleanup if necessary. 
            ' Terminate the operation. 
            Exit For 
        End If 
End Sub

Open in new window

Jacques Bourgeois (James Burger)PresidentCommented:
Understand what happens in the subroutine when it hangs, and find a workaround.

It might go into an infinite loop, trigger and Exception or something else. Most situations can be controlled once you understand where the problem is.

For instance, an infinite loop can be forced to exit after a certain number of iterations or certain delay.

An Exception can be trapped in a Try..Catch... End Try block and handled according to the Exception that is triggered.

The solution depends on the code that hangs.
DColinAuthor Commented:

I know what is causing the subroutine to hang it is that a page stops loading in a webbrowser control. How would I detect that a page has not loaded after ten minutes?
Jacques Bourgeois (James Burger)PresidentCommented:
Can you show us the code of the method and point to the line where it hangs?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.