Question : setup a background worker with a timeout net 2.0

I have a for/next  loop and would like to set it up to run a function in the background.  I also need this function to have timeout after 5 seconds and return a value if it failed.  I think I just want to limit it to one thread, but might like to have it run multiple threads later.  Any example on how to set this up would be great.

Answer : setup a background worker with a timeout net 2.0

I looked at the code and apparently the conversion tools do not work.  The VB syntax for creating threads and event handlers is quite different than C#.  I rewrote it in VB and this should work, God willing.  I've tested it in a VB compiler also in Visual Studio for compilation errors and there are none.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
Imports System.Threading

Module Module1

    Class SampleClass

        Private backgroundThread As Thread

        Private Sub StartBackgroundThread()
            backgroundThread = New Thread(New ParameterizedThreadStart(AddressOf DoWork)) '*****************dont see the sub to dowork

            backgroundThread.IsBackground = True
            ' timer to abort thread after 5 seconds
            Dim timer As New System.Timers.Timer(5000) ' 5 seconds

            AddHandler timer.Elapsed, AddressOf timer_Elapsed

            '***********dont have elapse as an option.  Also does not see the sub timer_elapsed

            ' start thread then start timer
            backgroundThread.Start()
            timer.Start()
        End Sub  ' end function StartBackgroundThread

        ' timer fired after 5 seconds function
        Private Sub timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
            Try
                If backgroundThread IsNot Nothing Then   '***********backgroundTimer is not defined
                    backgroundThread.Abort()             '*********backgroundTimer is not defined
                End If
            Catch
            End Try
        End Sub  ' end timer function

        ' do work function
        Private Sub DoWork(ByVal state As Object)

            Try
                ' do work here              
            Catch e As System.Threading.ThreadAbortException
                'handle timer expired here
            End Try
        End Sub
    End Class

    Sub Main()

    End Sub
End Module
Random Solutions  
 
programming4us programming4us