How to cancel background worker immediately?

Posted on 2008-06-20
Last Modified: 2009-10-15
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
Question by:nsgonline
  • 2
LVL 25

Expert Comment

ID: 21830780
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.

Author Comment

ID: 21836305
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?
LVL 25

Accepted Solution

SStory earned 500 total points
ID: 21845807
'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.



Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question