How to cancel background worker immediately?

Hello guys,

I am having problems in canceling background worker immediately, it takes time after cancellation. Actually i am calling web service to download specific data under do_work method and it can take time up to 10 to 20 secs, my requirement is that i have to immediately cancel that thread when user clicks next. On clicking next, next image/video/document will start downloading.

I did one try to get current thread and aborting that, but its dangerous as there can be other thread/background worker running along with this one.

Waiting for Reply,
Muhammad Abdullah Malik
Who is Participating?
SStoryConnect With a Mentor Commented:
'declare 7 bkworkers
    const NUM_THREADS=7

    Private WithEvents bkworker1 As New System.ComponentModel.BackgroundWorker
    Private WithEvents bkworker2 As New System.ComponentModel.BackgroundWorker
    Private WithEvents bkworker3 As New System.ComponentModel.BackgroundWorker
    Private WithEvents bkworker4 As New System.ComponentModel.BackgroundWorker
    Private WithEvents bkworker5 As New System.ComponentModel.BackgroundWorker
    Private WithEvents bkworker6 As New System.ComponentModel.BackgroundWorker
    Private WithEvents bkworker7 As New System.ComponentModel.BackgroundWorker

    Private bkworkeravailable(NUM_THREADS - 1) As Boolean

  Private Sub InitBackgroundWorkerStates()
        For b As Byte = 0 To NUM_THREADS - 1
            'set all workers as ready to go
            bkworkeravailable(b) = True
    End Sub

 'is there a worker thread that's not busy?
    Private Function WorkerAvailable(ByRef AvailableWorkerIndex As Byte) As Boolean
        Dim b As Byte
        'find an available worker thread
        For b = 0 To NUM_THREADS - 1
            If bkworkeravailable(b) = True Then
                AvailableWorkerIndex = b
                Return True
            End If

        '255 is an invalid thread; it and a false returned mean no thread available
        AvailableWorkerIndex = 255
        Return False
    End Function

  Public Sub New()

    End Sub

'where there is something do do,
           'loop until we find a worker thread available
                While Not WorkerAvailable(AvailableWorkerIndex)
                    'let's let the U/I have a chance to update
                    'sleep a little while waiting on threads
                End While

'When a worker is available use it
By calling

you will need to make that routine and based upon the index fire the correct one.  It is also better to make an object that represents the thing. It should know the index of the worker assigned. Here is my code for the first one:

If Not bkworker1.IsBusy Then
      bkworkeravailable(objWork.WorkerAssigned) = False
 End If

You will need 7 DoWork events, like this one:

Private Sub bkworker1_DoWork(ByVal sender As Object, ByVal e As  system.ComponentModel.DoWorkEventArgs) Handles bkworker1.DoWork
        Dim wd As Work = CType(e.Argument, Work)
       'do something with the work object

        'after work is performed, set the result to wd
        e.Result = wd
    End Sub

Then you will need code for each worker for "Finished"
   Private Sub bkworker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bkworker1.RunWorkerCompleted
        'the work finished; this thread got finished, results are in e.Result as a Work object
        'let's cast it and send to to HandleResults to be dealt with
        HandleResults(CType(e.Result, Work))
        'make this thread as availble in or little status array
        bkworkeravailable(0) = True
    End Sub

This should give you an idea of how to use it.
Unfortunately I don't know how to great an array of BackgroundWorker objects that use the withevents keyword...that would be a nice feature.


Does this article help?

I think you should have a pool or background worker threads and possibly a thread that manages them.
Maybe requests should be sent to a queue that the managing thread checks and assigns to one of the worker threads when it is available.
nsgonlineAuthor Commented:
given article cannot help, as i don't have any loop in do_work event. I am calling web service in it which can take some time. Service only ends, when it gets all the data. so it always return something even if i cancel background worker. Also my requirement is that i have to terminate immediately, say it should take less than a second or two to terminate. I have to call service to get next data and terminate current one if downloading any.

Can you please give me an example for your first statement?
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.