Solved

How to cancel background worker immediately?

Posted on 2008-06-20
5
2,140 Views
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,
Regards,
Muhammad Abdullah Malik
0
Comment
Question by:nsgonline
  • 2
5 Comments
 
LVL 25

Expert Comment

by:SStory
ID: 21830780
Does this article help?
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_21972221.html

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.
0
 

Author Comment

by:nsgonline
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?
0
 
LVL 25

Accepted Solution

by:
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
        Next
    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
        Next

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

  Public Sub New()
        InitializeComponent()

        InitBackgroundWorkerStates()
    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
                    Application.DoEvents()
                    'sleep a little while waiting on threads
                    System.Threading.Thread.Sleep(300)
                End While

'When a worker is available use it
By calling
AssignToWorker(AvailableWorkerIndex)

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
      bkworker1.RunWorkerAsync(objWork)
 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.

HTH,

Shane
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Introduction I needed to skip over some file processing within a For...Next loop in some old production code and wished that VB (classic) had a statement that would drop down to the end of the current iteration, bypassing the statements that were c…
When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
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…

705 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now