setup a background worker with a timeout net 2.0

chadmanvb
chadmanvb used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
You could use a background worker (http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx).  As for having it timeout, you could implement the function to start a timer when it is called; in the timer eventLapsed event handler, get a handle on the thread executing in the background (you could do that by setting the background thread to be a field in the class) and then calling the Abord method on the thread.  Inside the function, catch the ThreadAbortException that is raised when Abort is called on the thread (God willing) and do what you would like to do when time has expired.  When function is about to exit, it should disable the timer so it won't fire since it is not needed then.  All the timer management can be done outside of function code also so not to add extra functionality to the background thread function.  The timer event handler should use a try/catch in the event that the timer fires just before the function completes and the ThreadAbort is called on a thread that has finished.

Author

Commented:
That sounds like what I am looking for.  Would you have an example of how to set this up?

Commented:
Here is an examle, please ensure it fits with your design
class SomeClass
{
    Thread backgroundThread;
    private void StartBackgroundThread()
    {
       backgroundThread = new Thread((new ParameterizedThreadStart(DoWork));
       // or Thread backgroundThread = new Thread(DoWork); if you compiler is 3.0 or greater
       backgroundThread.IsBackground = true;
       
       // timer to abort thread after 5 seconds
       System.Timers.Timer timer = new System.Timers.Timer(5000); // 5 seconds
       timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
       timer.Start();


   

Commented:
opps, that got posted before I was finished, here it is again:

Here is an examle, please ensure it fits with your design
class SomeClass
{
    Thread backgroundThread;
    private void StartBackgroundThread()
    {
       backgroundThread = new Thread((new ParameterizedThreadStart(DoWork));
       // or Thread backgroundThread = new Thread(DoWork); if you compiler is 3.0 or greater
       backgroundThread.IsBackground = true;
       
       // timer to abort thread after 5 seconds
       System.Timers.Timer timer = new System.Timers.Timer(5000); // 5 seconds
       timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

      // start thread then start timer
       backgroundThread.Start();
       timer.Start();
   } // end function StartBackgroundThread

   // timer fired after 5 seconds function
   void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
         try
         {
             if(backgroundTimer != null)
             {
                  backgroundTimer.Abort();
             }
       }
         catch{}
     }// end timer function


   // do work function
    private void DoWork(object state)
    {
        try
        {
            // do work here
         }
         catch(System.Threading.ThreadAbortException e) { // handle timer expired here }
     }

God willing, that should be a good sample
       

Author

Commented:
Opps, I should have mentioned I was using vb, not c#.  I give a shot and converting this, but I'm not very good at it.  Thanks!

Commented:
there is a slight syntax difference but everything is basically the same

Commented:
Here is faisall's code in VB.Net. I converted it using DeveloperFusions conversion tool. You can find it here.

Class SomeClass

    Private backgroundThread As Thread

    Private Sub StartBackgroundThread()
          backgroundThread = New Thread(New ParameterizedThreadStart(DoWork))
          ' or Thread backgroundThread = new Thread(DoWork); if you compiler is 3.0 or greater
          backgroundThread.IsBackground = True

          ' timer to abort thread after 5 seconds
          Dim timer As New System.Timers.Timer(5000)' 5 seconds
          timer.Elapsed += New System.Timers.ElapsedEventHandler(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(sender As Object, e As System.Timers.ElapsedEventArgs)
          Try
                              If backgroundTimer IsNot Nothing Then
                    backgroundTimer.Abort()
               End If
          Catch
          End Try
    End Sub  ' end timer function

    ' do work function
    Private Sub DoWork(state As Object)
          
          Try
              ' do work here             
          Catch e As System.Threading.ThreadAbortException
              'handle timer expired here
          End Try
    End Sub

End Class

Commented:
Oops, I forgot to post the conversion tool link...

http://www.developerfusion.com/tools/

Author

Commented:
Thanks I love it converted it, but the syntex is still not correct.  I have not done this before and not sure what to change.

Commented:
What errors are you getting?  Note that you'll need to import System.Threading

Author

Commented:
I did import system.threading.  Here are the errors I have

   Private backgroundThread As Thread

    Private Sub StartBackgroundThread()
        backgroundThread = New Thread(New ParameterizedThreadStart(DoWork)) '*****************dont see the sub to dowork
        ' or Thread backgroundThread = new Thread(DoWork); if you compiler is 3.0 or greater
        backgroundThread.IsBackground = True
        ' timer to abort thread after 5 seconds
        Dim timer As New System.Timers.Timer(5000) ' 5 seconds
       
        timer.Elapse += New System.Timers.ElapsedEventHandler(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 backgroundTimer IsNot Nothing Then   '***********backgroundTimer is not defined
                backgroundTimer.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
Commented:
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.


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

Open in new window

Commented:
Has this solution worked for you?  If so please close it.

Author

Commented:
Just got a chance to look at this again this morning.  Looks like I'm in good shape.  Thanks!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial