I have a progress bar and backgroundworker in VB.Net that I would want to work in a different form as given below:
Form1()
{
MaxRows = 10
for i = 0 to MaxRows then
// Update my value on the progressbar
....
next
}
ProgressBarForm
Private Sub ProgressBarForm_Shown(sender As Object, e As EventArgs) Handles Me.Shown
TransferProgressBar.Visible = True
ProgressBarBackgroundWorker.RunWorkerAsync()
End Sub
Private Sub ProgressBarBackgroundWorker_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles ProgressBarBackgroundWorker.DoWork
For i = 0 To TransferProgressBar.Maximum
'Dim Percentage As Integer = Math.Round(((i / (TransferProgressBar.Maximum - TransferProgressBar.Minimum)) * 100))
ProgressBarBackgroundWorker.ReportProgress(i / 100)
Next
End Sub
Private Sub ProgressBarBackgroundWorker_ProgressChanged(sender As Object, e As ComponentModel.ProgressChangedEventArgs) Handles ProgressBarBackgroundWorker.ProgressChanged
TransferProgressBar.Value = e.ProgressPercentage
PercentageLabel.Text = "Processing....." & TransferProgressBar.Value.ToString() & "%"
End Sub
Private Sub ProgressBarBackgroundWorker_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles ProgressBarBackgroundWorker.RunWorkerCompleted
MsgBox("Task Completed!")
Me.Close()
End Sub
How can I update my progressbar value using the backgroundworker from another form/Sub? Kindly let me know. I'm getting a bit confused here.
You seem to have it back to front. Rather than the
BackgroundWorker
handling theProgressBar
updates, use the BGW to do the time consuming work. Then at intervals you can provide updates for the ProgressBar/Form using the built-inReportProgress
method.Normally, you cannot (directly) access UI controls, like a
ProgressBar
, from a thread other than the one it was created on (ie the UI thread). TheReportProgress
event is raised on the original/UI thread to make basic progress reporting easy.However, it is pretty much limited to only that. To do more, for instance post results of the long process to a
ListBox
, you would use a Delegate to update the control on the other/UI thread.The Form with the long running task
Note that normally using
Thread.Sleep
freezes the UI. That doesnt happen here because it is theBackgroundWorker
not the UI thread which is put to sleep.The Form with the progress bar: