I have seen this problem before but I haven’t seen an answer to the question that applied to my particular case. I have a BackgroundWorker running in my VB form, as well as a progress bar and some labels. I also (if it’s important) have a WebBrowser on my form, but it isn’t affected by the thread.
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim ints As Integer = Int(InputBox("What number to start at?"))
Dim inte As Integer = Int(InputBox("What number to end at?"))
ToolStripStatusLabel1.Text = "0 / " & inte - ints
ToolStripProgressBar1.Maximum = inte
ToolStripProgressBar1.Minimum = ints
ToolStripProgressBar1.Style = ProgressBarStyle.Continuous
Try
For z As Integer = ints To inte
ToolStripProgressBar1.Value = z
ToolStripStatusLabel1.Text = z & "/" & inte
'do some stuff here
catch etc
next
When the loop is running, sometimes it stops and the progress bar disappears. Any idea why?
Btw the only thing I’m doing in there is running an httpwebrequest and handling the string.
This is likely to do with the fact that you’re setting the value of a user interface object (
ToolStripProgressBar1) within theBackgroundWorker‘sDoWorkmethod which is running in it’s own thread, separate from the User Interface thread which theToolStripProgressBar1is in.As per the Note on this MSDN page:
What you should do is to change the code that’s inside the loop (
For z As Integer = ints To inte) so that instead of setting theValueandTextproperties directly, you call theBackgroundWorker‘sReportProgressmethod. This raises theProgressChangedevent which you can then handle on the main UI thread. It’s in here that you can then safely access the properties of User Interface components and objects.