1

Is there any way to cancel backgroundworker after x second (ie. timeout 5 second) if the worker is still busy processing a single code line? (never go to the end of While loop to check for CancellationPending)? Example:

Private Sub DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        Dim worker As BackgroundWorker = DirectCast(sender, BackgroundWorker)
        While Not worker.CancellationPending
            Dim args As ArgumentType = CType(e.Argument, ArgumentType)
            Try
            process #1
            process #2 --> hanging here. Never throw exception.
            ...
            process #n

            Catch ex as Exception
            'Never come here
            End Try
        End While
End Sub
Kara
  • 6,115
  • 16
  • 50
  • 57
Đức Nguyễn
  • 606
  • 3
  • 9
  • 19
  • Possible duplicate of http://stackoverflow.com/questions/4732737/how-to-stop-backgroundworker-correctly – Software Engineer Jan 26 '13 at 12:37
  • That's not possible, you'll need to fix the bug. If you can't then you'll need to run this code in another process that you can Kill(). – Hans Passant Jan 26 '13 at 14:00
  • I use a 3rd party dll in DoWork of the Backgroundworker. That's a bug of that dll :(. Why the Backgroundworker doesnt have something like Join() in thread :( – Đức Nguyễn Jan 26 '13 at 15:47

1 Answers1

0

You can solve this problem in two ways:

  1. by leveraging some support in the library as suggested by Henk Holterman in this answer -- but I understand that this is not your case;
  2. as suggested by Hans Passant and by this answer by HackedByChinese, you can spawn a new task/thread in which you can do the work and poll for cancellation from the DoWork handler -- when cancellation is requested, you simply ignore the outcome of the task (or manage it in a way that does not interfere with subsequent computation).
  3. if process #2 is in fact a program, you can start your process and then leverage Process.WaitForExit(http://msdn.microsoft.com/en-us/library/ty0d8k56.aspx) -- that is, you wait for a while for the process to exit and then check if cancellation is requested.
Community
  • 1
  • 1
edymtt
  • 1,778
  • 1
  • 21
  • 37