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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to debug this code 7 65
Excel - Save a copy of work book 13 96
message box in access 4 55
Spell Check in VB6 13 147
There are many ways to remove duplicate entries in an SQL or Access database. Most make you temporarily insert an ID field, make a temp table and copy data back and forth, and/or are slow. Here is an easy way in VB6 using ADO to remove duplicate row…
When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
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…

732 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