How to cancel background worker immediately?

Posted on 2008-06-20
Medium Priority
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 2000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
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…
Suggested Courses
Course of the Month14 days, 4 hours left to enroll

807 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