473,385 Members | 1,474 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

How to Stop and Restart a BackGroundWorker

Hi. I'm working on a project in which use a BackGroundWorker control between two forms.

I need to Cancel and immediately to restart the BackGroundorker from the same event. The problem is that: when BackGroundWorker.CancelAsync(), apparently the thread does not cancel and when it gets to BackGroundWorker.RunWorkerAsync(), the exception "BackgroundWorker is busy" is thrown.

So, how can I cancel and restart the backgroundworker from the same event.

(Note: I tried with the Threading Class too and I got a similar problem. When use Thread.Abort() or Thread.Suspended(), the thread is stopped but it cannot restart again.)
Jun 19 '13 #1
12 6264
Mihail
759 512MB
I try a response only because your post is 3 days older.
Define a public variable. Say: Public StopRun As Boolean.
Before starting the BackGroundorker set this variable to False.
From the BackGroundorker verify from time to time this variable:
If StopRun Then Exit

Set to True this variable from the main code when you wish to stop the BackGroundorker.

Sorry, my English is not very good. Hope you get the idea.
Jun 22 '13 #2
Thanks Mihail but it does not work propertly. I used a boolean 'StopRun' and when it is applied from a button or from another independent method works, but remember I need to stop and restart the thread from the same method.
Basically, I did StopRun on True, then sleep some milisecs and then StopRun on False and call the thread again. But the called method does not start from the begining or it just does not stop until finish.

I'm still looking for.
Jun 25 '13 #3
Mihail
759 512MB
What you are trying to do ?
Why you need to stop the BackGroundorker for miliseconds.
Do you know the DoEvents statement ?

If you explain WHY you wish to pause that BackGroundorker, maybe we can find a solution.
Jun 25 '13 #4
Ok. I will try to be clear.
See the code below:

Expand|Select|Wrap|Line Numbers
  1. Form_List
  2.   -ListView
  3.   Public Sub Fill_ListView()
  4.     (every code to fill the ListView)
  5.      Linq
  6.      ImageList --> Module1.FindImage(Image As Bitmap)
  7.      ListViewItem
  8.      etc.
  9.  
  10. ---------------------
  11.  
  12. Form_PPAL
  13.   Private MyList_1 As Form_List
  14.   Private MyList_2 As Form_List
  15.  
  16.   Me.MyList_1.Fill_ListView
  17.   Me.MyList_2.Fill_ListView
  18.  
Ok. The application of course has a lot of things I do not show. I just show you the important issue.

The problem comes when it has to find each image of each item and there are a lot of items to show. It takes a lot of time. So, I suppose to use a thread to populate the ListViews.

In the first sight the thread works fine but the user can switch a radios buttons ir order to visualize another items.

So, just imagine when the user click on a radio button, the application has to stop the loading of items in either ListViews and then needs to start over again with populate de ListView with other items. That's all.

Finally, I've heard about DoEvents but never have used it. I'm gonna try.

Thanks.
Jun 25 '13 #5
Mihail
759 512MB
Yep.
Seems that I have had a good feeling.
I'm pretty sure that the DoEvents statement is the answer to your issue

Say you have a long cycle:
Expand|Select|Wrap|Line Numbers
  1. For i = 1 to 1000000000000000000000000000000000
  2.     For j = 1 to 1000000000000000000000000000000000
  3.         For k = 1 to 1000000000000000000000000000000000
  4.             DoEvents
  5.             'Other code
  6.         Next k
  7.     Next j
  8. Next i
  9. MsgBox("OK - I have finished
The DoEvents statement will allow you to do anything else with your computer WHILE the cycle IS RUNNING.
No need to stop this cycle.
And, when I say anything is really ANYTHING:
You can see a movie, run other procedures, drink a beer :)

Cheers !
Jun 26 '13 #6
jeje... I appreciate all your good intention. Really I do. But, my friend, that´s not the solution.

When user changes a radiobutton option or wants to go to another place inside application, he should not wait for ListView loading. Besides, if user make two, three or more changes (clicks, etc), all of them are placed inside memory waiting to act. It is like when a program does not respond and suddenly every click you did appers one behind other and other.

That's it. When user clicks radiobutton or any other button, the app must terminate the ListView loading, take de new values and then populates the ListView once again from benining with new values.

It would be great if we can do something like this:

Expand|Select|Wrap|Line Numbers
  1. Private Sub Fill_ListView()
  2.  
  3.  If Thread1.ThreadState = Threading.ThreadState.Running Then
  4.     Thread1.Abort()
  5.     <some code>
  6.  End If
  7.  
  8.  Thread1.Start()
  9.  
  10. End Sub
  11.  
Jun 26 '13 #7
Mihail
759 512MB
And this is fairly easy to obtain using DoEvents.

Note that (see my previous post) you must allow events in the most interior cycle to ensure that DoEvents is executed with the maximum frequency.

Put in a form 5 command buttons:
cmdStart
cmdPause
cmdContinue
cmdRestart
cmdStop

and in the Form module copy this code:

Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Dim ThreadAction As String
  5.  
  6. Private Sub cmdContinue_Click()
  7.     ThreadAction = "Continue"
  8. End Sub
  9.  
  10. Private Sub cmdPause_Click()
  11.     ThreadAction = "Pause"
  12. End Sub
  13.  
  14. Private Sub cmdRestart_Click()
  15.     ThreadAction = "Restart"
  16. End Sub
  17.  
  18. Private Sub cmdStart_Click()
  19.     Call FillListView
  20. End Sub
  21.  
  22. Private Sub cmdStop_Click()
  23.     ThreadAction = "Stop"
  24. End Sub
  25.  
  26. Private Sub FillListView()
  27.     MsgBox ("Start cycle.")
  28.  
  29.     Do
  30.         MsgBox ("Now I read (new) values for variables and (new) settings")
  31.         ThreadAction = ""
  32.         Do
  33.             DoEvents
  34.             If ThreadAction = "Pause" Then
  35.                 MsgBox ("I'll take a break")
  36.                 Do While ThreadAction = "Pause"
  37.                     DoEvents
  38.                 Loop
  39.                 MsgBox ("The break was too short for me")
  40.             End If
  41.             If (ThreadAction = "Restart") Or (ThreadAction = "Stop") Then
  42.         Exit Do
  43.             End If
  44.         Loop
  45.     Loop Until ThreadAction = "Stop"
  46.  
  47.     MsgBox ("Stoped by user")
  48. End Sub
  49.  

Be sure that every command button "see" it's events.
.
.
Jun 26 '13 #8
It's ok when buttons is used. But that's not the idea.
If you want you can download a simple example I made in the next link:

http://leoweb.hol.es/VB/

'Threarding_1.zip'

It is a very simple example, but it has the principal idea.

When user click on either button or changes radiobuttons, both ListView should stop their work and restart again from the begining.
Jun 26 '13 #9
Mihail
759 512MB
I understand that.
But the radio button also has an event you can use: OnClick, OnChange, MouseDown, MouseUp etc.
I give you an idea about how DoEvents work.
If you don't wish even to try or you think that is a better way... Good luck !
Jun 26 '13 #10
In fact, I did try DoEvent but it was the same problem. Definitively, I gonna have to change the way I'm trying to do it.

Thanks again for your support.
Jun 26 '13 #11
Killer42
8,435 Expert 8TB
I'd just like to point out that you're likely to find much more useful information about threading in the VB.Net forum. This one is for VB6. VB6 is incredibly old, and threading was never much of an issue.
Jul 9 '13 #12
Hello!

If you still need it,
Check this...

add 2 radiobuttons
add one textbox << this only for example put now
add one listbox << u later put listview
add one module

and use this code:

Expand|Select|Wrap|Line Numbers
  1. Public Class Form1
  2.  
  3.     Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
  4.         txt = CType(sender, Control).Text
  5.  
  6.         If work = False Then myEventHandler() Else restart = True '<< Important this line at the end only
  7.     End Sub
  8.  
  9.     Private Sub RadioButton1_Click(sender As Object, e As EventArgs) Handles RadioButton1.Click, RadioButton2.Click
  10.         txt = CType(sender, RadioButton).Text
  11.  
  12.         If work = False Then myEventHandler() Else restart = True '<< Important this line at the end only
  13.     End Sub
  14. End Class
  15.  
  16.  
  17. Module Module1
  18.     Public work As Boolean
  19.     Public restart As Boolean
  20.     Public i As Long
  21.     Public txt As String
  22.  
  23.     Public Sub myEventHandler()
  24.         ' hear put the startup staff
  25.         i = 0 : Form1.ListBox1.Items.Clear() : restart = False '<< start/restart staff
  26.         Form1.Text = "Start"
  27.         work = True
  28.  
  29.         ' hear begin the core... !
  30.         Do Until i = 10000
  31.             Application.DoEvents()
  32.  
  33.             ' hear put everything u need for restart
  34.             If restart = True Then 'Reset
  35.                 i = 0 : Form1.ListBox1.Items.Clear() : restart = False '<< start/restart staff
  36.             End If
  37.  
  38.             ' hear is main work
  39.             i = i + 1 : Form1.ListBox1.Items.Add(txt & "  " & Int(Rnd() * 999999))
  40.             ' in this example put 10000 random numbers with sorted order
  41.         Loop
  42.  
  43.         ' and hear put the finish staff
  44.         work = False
  45.         Form1.Text = "Finish"
  46.     End Sub
  47.  
  48. End Module
  49.  

this is a basic idea...
propably if use this idea with background worker
have better results...
Oct 14 '13 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: stash | last post by:
When I stop all DB2 services on our Unix box - I still can see the following two DB2 processes running: root 20410 1 0 Oct 28 - 4:16 /usr/opt/db2_08_01/bin/db2fmcd db2as 21780 ...
0
by: felecha | last post by:
Is there a way to write a Service so that it will fail? I'm working on a Service written in VB.Net, that supports an application we are building, and I want to make sure that it can restart...
6
by: Leonardo Curros | last post by:
Hello, I would like to know what's the best way to restart one service. I would like to do it from the service itself. Is this possible? I try it with ServiceController.stop()...
5
by: juky | last post by:
Hi all, I have 3 running threads chencking for something in my application. Based on that I need to stop some of them safely wait for something else and restart. Sleep is not good in my case...
1
by: JJ | last post by:
Hi, I was wondering what reasons would you have for needing to restart IIS. If I drop a dll into the bin directory and wanted to make sure the old dll wasn't being used anymore or maybe there...
5
by: elziko | last post by:
I know I can stop my thread by using the CancelAsync method of the BackgroundWorker but that requires me to monitor the value of the CancellationPending property in my BackgroundWorker.DoWork...
5
by: Torben Laursen | last post by:
Hi My interface calls a C++ dll that runs a slow calculations. So I call the dll inside a BackgroundWorker thread, and that all works fine. But how can I stop the thread if the user wants to?...
7
by: shai | last post by:
I am working at .net 1.1, writing in c#. I have windows service with a COM object. Every unexpected time The COM object throw an error that make my service get stuck (do not respond). I can catch...
0
by: Emanuele | last post by:
I have write a program using MS Visual studio C++ 7.0 (platform Windows XP professional). I'm not using .NET. This program save data in a SQL server 2000 database using ADO. Everything works...
4
by: Bob | last post by:
Hi, I would like to periodically start and stop mysql on a schedule using something like the Windows scheduler. Does anyone know a good way to do this? Thanks, Bob
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.