How to show or load Main Form (MDIParent1) after RunWorkerCompleted in VB.NET - vb.net

I have a many Splash Form, MDIParent Form and others form. My Scenario process like this: Project Statup - SPlash Form, After Splash Form show first time and check some files, etc and after checking will be show MDIParent1 and splash form will close automatically.
This below is my code inside Splash form:
Public Class frmSplash
Dim m_CountTo As Integer = 0 ' How many time to loop.
Private Sub My_BgWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles My_BgWorker.DoWork
For i As Integer = 0 To m_CountTo
' Has the background worker be told to stop?
If My_BgWorker.CancellationPending Then
' Set Cancel to True
e.Cancel = True
Exit For
End If
System.Threading.Thread.Sleep(100) ' Sleep for 1 Second
' Report The progress of the Background Worker.
My_BgWorker.ReportProgress(CInt((i / m_CountTo) * 100))
SetLabelText_ThreadSafe(Me.lblPercent, FormatPercent(i / m_CountTo, 2))
If i = 10 Then
SetLabelText_ThreadSafe(Me.lblMessages, "Initializing..")
ElseIf i = 40 Then
SetLabelText_ThreadSafe(Me.lblMessages, "Checking Mysql Service..")
ElseIf i = 50 Then
If CheckIfServiceIsRunning("MySql") = False Then
' Is the Background Worker do some work?
If My_BgWorker.IsBusy Then
'If it supports cancellation, Cancel It
If My_BgWorker.WorkerSupportsCancellation Then
' Tell the Background Worker to stop working.
My_BgWorker.CancelAsync()
End If
End If
SetButton_ThreadSafe(Me.btnExit, True)
Exit Sub
End If
ElseIf i = 70 Then
SetLabelText_ThreadSafe(Me.lblMessages, "Checking Internet Connection..")
ElseIf i = 80 Then
If CheckURL("http://www.google.com") = False Then
SetLabelText_ThreadSafe(Me.lblMessages, "No Internet Connection..")
End If
Next
End Sub
Private Sub My_BgWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles My_BgWorker.ProgressChanged
' Update the progress bar
Me.ProgressBar1.Value = e.ProgressPercentage
End Sub
Private Sub My_BgWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles My_BgWorker.RunWorkerCompleted
If e.Cancelled Then
Me.lblMessages.Text = "Cancelled"
Else
Me.lblMessages.Text = "Completed"
My_BgWorker.CancelAsync()
Me.Close()
MDIParent1.Show()
End If
End Sub
Delegate Sub SetLabelText_Delegate(ByVal [Label] As Label, ByVal [text] As String)
' The delegates subroutine.
Private Sub SetLabelText_ThreadSafe(ByVal [Label] As Label, ByVal [text] As String)
' InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If [Label].InvokeRequired Then
Dim MyDelegate As New SetLabelText_Delegate(AddressOf SetLabelText_ThreadSafe)
Me.Invoke(MyDelegate, New Object() {[Label], [text]})
Else
[Label].Text = [text]
End If
End Sub
Delegate Sub SetButton_Delegate(ByVal [Button] As Button, ByVal [visible] As Boolean)
' The delegates subroutine.
Private Sub SetButton_ThreadSafe(ByVal [Button] As Button, ByVal [visible] As Boolean)
' InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If [Button].InvokeRequired Then
Dim MyDelegate As New SetButton_Delegate(AddressOf SetButton_ThreadSafe)
Me.Invoke(MyDelegate, New Object() {[Button], [visible]})
Else
[Button].Visible = [visible]
End If
End Sub
Private Sub frmSplash_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Set the count to 100
m_CountTo = 100
' Start the Background Worker working
My_BgWorker.RunWorkerAsync()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
' Is the Background Worker do some work?
If My_BgWorker.IsBusy Then
'If it supports cancellation, Cancel It
If My_BgWorker.WorkerSupportsCancellation Then
' Tell the Background Worker to stop working.
My_BgWorker.CancelAsync()
End If
End If
' Enable to Start Button
Me.btnExit.Enabled = True
' Disable to Stop Button
Me.btnExit.Enabled = False
Application.Exit()
End Sub
End Class
Anyone can help me, whats the best way to show MDIParent (the main form) in sub RunWorkerCompleted, after splash form finish to loading.
In my code above, MDIParent1 cannot show correctly because after show, application closed/terminated.

In Project --> Properties, set your MDIParent as the "Startup form", and set your Splash Form as the "Splash form".
Now place all of your initialization checks in the Load() event of the MDIParent without using any Threading or BackgroundWorkers. The Splash Form will display for as long as the Load() event takes to complete, then will close automatically.
To update the splash from your MDIParent, cast My.Application.SplashScreen to your Splash Form type, and use delegates/Invoke() as you're already doing.
Here's a silly example:
Public Class frmMdiParent
Private Sub frmMdiParent_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' initialization...
Dim splash As frmSplash = DirectCast(My.Application.SplashScreen, frmSplash)
Dim numberSteps As Integer = 10
For i As Integer = 1 To numberSteps
splash.Invoke(Sub()
splash.Label1.Text = "Step " & i & " of " & numberSteps
End Sub)
System.Threading.Thread.Sleep(1000)
Next
' some other stuff...
Dim child As New Form
child.MdiParent = Me
child.Text = "Some MdiChild..."
child.Show()
End Sub
End Class

Related

How Can I Speed This Up? Updated Code Better but Not Good Enough

The code below works perfectly for small directories, but when I try it on a larger one (only 8,500 files) it takes about an hour. All it's doing is copying files listed in a dictionary from one directory to another. It's the bgworker_DoWork() method that is taking the time. It populates the dictionary in a second or two, but then the grinding begins. I've even tried commenting out the update progress code to see if that helps - it didn't.
One thing I noticed: when I had the progress indicator on the first 10% of files finished pretty quickly, but they each slowed more after that. I'd appreciate any help.
Private Sub StartButton_Click(sender As Object, e As EventArgs) Handles StartButton.Click
'Set the count to 30
m_CountTo = intLVIndex - 1
' Disable the start button
Me.StartButton.Enabled = False
' Enable to stop button
Me.StopButton.Enabled = True
' Start the Background Worker working
Dim dict As New Dictionary(Of String, String)
For i As Integer = 0 To m_CountTo
dict.Add(Me.LVFiles.Items(i).SubItems(0).Text,
Me.LVFiles.Items(i).SubItems(3).Text)
Next
LabelTask.Visible = True
LabelTask.Text = "Copying"
LabelStatus.Visible = True
ProgressBar1.Visible = True
BackgroundWorker1.RunWorkerAsync(dict)
End Sub
Private Sub StopButton_Click(sender As Object, e As EventArgs) Handles StopButton.Click
' Is the Background Worker do some work?
If BackgroundWorker1.IsBusy Then
'If it supports cancellation, Cancel It
If BackgroundWorker1.WorkerSupportsCancellation Then
' Tell the Background Worker to stop working.
BackgroundWorker1.CancelAsync()
End If
End If
' Enable to Start Button
Me.StartButton.Enabled = True
' Disable to Stop Button
Me.StopButton.Enabled = False
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim counter As Integer = -1
Dim prgctr As Integer = 0
For Each kvp In DirectCast(e.Argument, Dictionary(Of String, String))
counter += 1
' Has the background worker been told to stop?
If Me.BackgroundWorker1.CancellationPending Then
' Set cancel to True
e.Cancel = True
Exit For
End If
strSourceFilePath = kvp.Key
strDestFilePath = kvp.Value
' Do the file copy here
My.Computer.FileSystem.CopyFile(strSourceFilePath, strDestFilePath, overwrite:=False)
'If prgctr = 50 Then
' 'Report the progress of the background worker
' Me.BackgroundWorker1.ReportProgress(CInt((counter / m_CountTo) * 100), counter)
' prgctr = 0
'Else
' prgctr += 1
'End If
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
' Update the progress bar
'Me.ProgressBar1.Value = e.ProgressPercentage
'Me.LVFiles.Items(Convert.ToInt32(e.UserState)).Selected = True
'Me.LabelStatus.Text = e.ProgressPercentage.ToString & "%"
End Sub
Private Sub My_BgWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled Then
Me.LabelStatus.Text = "Cancelled"
Else
Me.LabelStatus.Text = "Completed"
End If
End Sub
' The delegate
Delegate Sub SetLabelText_Delegate(ByVal [Label] As Label, ByVal [text] As String)
' The delegates subroutine.
Private Sub SetLabelText_ThreadSafe(ByVal [Label] As Label, ByVal [text] As String)
' InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If [Label].InvokeRequired Then
Dim MyDelegate As New SetLabelText_Delegate(AddressOf SetLabelText_ThreadSafe)
Me.Invoke(MyDelegate, New Object() {[Label], [text]})
Else
[Label].Text = [text]
End If
End Sub

How to wait for BackgroundWorker to finish without killing ProgressBar?

The application is doing a lot more than this, but I have narrowed down the issue with the example below.
When bgwDone.WaitOne() is commented out, the progress bar works fine, cancel button is effective, but execution continues before the background process is complete.
When bgwDone.WaitOne() is applied, the ProgressForm is visible but not enabled, so processing cannot be cancelled and progress bar does not refresh, and the most confusing part, Msgbox("1") does not execute. I only see Msgbox("2") after the background worker finishes. I am utterly perplexed.
Imports System.ComponentModel
Public Class Form1
Private WithEvents bgw As BackgroundWorker
Private Event bgwCancelled()
Private bgwDone As New System.Threading.AutoResetEvent(False)
'Allows ProgressForm to cancel execution
Public Sub bgwCancelAsync()
RaiseEvent bgwCancelled()
End Sub
Private Sub bgw_Cancelled_by_ProgressForm() Handles Me.bgwCancelled
bgw.CancelAsync()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Cursor = Cursors.WaitCursor
bgw = New BackgroundWorker
bgw.WorkerReportsProgress = True
bgw.WorkerSupportsCancellation = True
If bgw.IsBusy = False Then
ProgressForm.Show()
bgw.RunWorkerAsync(10)
End If
'********THIS LINE: bgwDone.WaitOne() MAKES A BIG DIFFERENCE*******
bgwDone.WaitOne()
MsgBox("1")
MsgBox("2")
Cursor = Cursors.Default
End Sub
'BackgroundWorker.RunWorkerAsync raises the DoWork event
Private Sub bgw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgw.DoWork
Dim numToDo As Integer = CInt(e.Argument)
For n As Integer = 1 To numToDo
If bgw.CancellationPending Then
Exit For
End If
System.Threading.Thread.Sleep(200)
bgw.ReportProgress(n * 10)
Next
bgwDone.Set()
End Sub
'ReportProgress raises the ProgressChanged event
Private Sub bgw_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles bgw.ProgressChanged
ProgressForm.UpdateProgress(e.ProgressPercentage)
End Sub
Private Sub bgw_RunWorkerCompleted(sender As Object,
e As RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
ProgressForm.Close()
End Sub
And my form with the ProgressBar:
Public Class ProgressForm
Private Sub ButtonCancel_Click(sender As Object, e As EventArgs) Handles ButtonCancel.Click
Form1.bgwCancelAsync()
End Sub
Public Sub UpdateProgress(pct As Integer)
ProgressBar1.Value = pct
ProgressBar1.Refresh()
End Sub
End Class
I am not sure what you are trying to accomplish. But it almost seems like some of your code is trying to defeat the purpose of a BackGroundWorker:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Cursor = Cursors.WaitCursor
bgw = New BackgroundWorker
...
If bgw.IsBusy = False Then
ProgressForm.Show()
bgw.RunWorkerAsync(10)
End If
bgwDone.WaitOne()
MsgBox("1")
MsgBox("2")
Cursor = Cursors.Default
End Sub
The purpose of a BackgroundWorker is to do some long running task on another thread and leave the UI responsive. I am not sure that a task that only "takes several seconds" qualifies as a long running task.
Given that, why use the WaitCursor while the BGW runs? The point to leaving the UI resposive is to allow the user to do other things in the meantime.
The test for bgw.IsBusy can never, ever be true - you just created it 3 lines earlier. Click the button again and you will create another BGW.
The rest of the code in the click looks like you want or expect the code to continue on the next line after the BGW completes. That's not how it works.
If the app cannot continue without those tasks being completed, disable anything that lets the user go elsewhere until the worker completes or:
Forego the worker and put the form in wait mode (Me.UseWaitCursor) until the stuff is loaded. This doesn't rule out a ProgressBar.
A dedicated Progress Form can make sense in cases where the app will use various workers at various times. A StatusBar can contain a ProgressBar and is much more subtle (and perhaps appropriate since it is a status element).
So, revised and using a form instance for the progress reporter:
MainForm
Private WithEvents bgw As BackgroundWorker
Private frmProg As ProgressForm
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
bgw = New BackgroundWorker
End Sub
Private Sub btnLoadAll_Click(sender As Object, e As EventArgs) Handles btnLoadAll.Click
bgw.WorkerReportsProgress = True
bgw.WorkerSupportsCancellation = True
If bgw.IsBusy = False Then
' create ProgressForm instance if needed
If frmProg Is Nothing Then frmProg = New ProgressForm
frmProg.Show()
bgw.RunWorkerAsync(78)
End If
btnLoadAll.Enabled = False
End Sub
Private Sub bgw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgw.DoWork
' multiple workers can use the same event
Dim thisWorker = DirectCast(sender, BackgroundWorker)
Dim count = Convert.ToInt32(e.Argument)
For n As Integer = 1 To count
If thisWorker.CancellationPending Then
Exit For
End If
' Fake work:
System.Threading.Thread.Sleep(50)
' dont assume the size of the job if
' there are multiple BGW or tasks
thisWorker.ReportProgress(Convert.ToInt32((n / count) * 100))
Next
End Sub
Private Sub bgw_ProgressChanged(sender As Object,
e As ProgressChangedEventArgs) Handles bgw.ProgressChanged
frmProg.UpdateProgress(e.ProgressPercentage)
End Sub
Private Sub bgw_RunWorkerCompleted(sender As Object,
e As RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
If e.Error IsNot Nothing Then
'... ToDo
ElseIf e.Cancelled Then
'... ToDo
Else
frmProg.Close()
' avoid 'cannot access disposed object':
frmProg = Nothing
Me.btnNextStep.Enabled = True
btnLoadAll.Enabled = True
End If
End Sub
Rather than enabling a "Next" button, the app could automatically proceed. It depends on the app.

Using a timer to update form - VB.Net

I want to display the status of aspects of my application on a form.
I tried adding a timer to the form. Every 10 seconds the timer runs and checks a database for a particular status, then changes elements on the form based on the status.
This works fine for changing the colour of menu items, but when I try and make an image (in)visible on the form, I get a cross-thread error.
Should I be using a timer, Backgroundworker or something else?
Does someone have a basic bit of code that will do this elegantly?
Private WithEvents tmrMain As New System.Timers.Timer(10000)
Private Sub frmMaster_Load(sender As Object, e As EventArgs) Handles Me.Load
tmrMain.Enabled = True
tmrMain.Start()
End Sub
Private Sub tmrMain_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles tmrMain.Elapsed
Dim TRunning As Boolean = True
TRunning = BTools.CheckImportRunningStatus '' This gets the on/off status from the DB
If TRunning Then
miFileMYOBImport.ForeColor = Color.Red '' Change menu color
pbMYOBDownload.Visible = True '' Make image visible
Else
miFileMYOBImport.ForeColor = Color.DarkGreen
pbMYOBDownload.Visible = False
End If
End Sub
Try:
Private Sub MakeImageVisible(ByVal control As Control, ByVal visible As Boolean)
If control.InvokeRequired Then
control.BeginInvoke(New Action(Of Control, Boolean)(AddressOf MakeImageVisible), control, visible)
Else
control.Visible = visible
End If
End Sub
Private Sub tmrMain_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles tmrMain.Elapsed
Dim TRunning As Boolean = True
TRunning = BTools.CheckImportRunningStatus '' This gets the on/off status from the DB
If TRunning Then
miFileMYOBImport.ForeColor = Color.Red '' Change menu color
Else
miFileMYOBImport.ForeColor = Color.DarkGreen
End If
MakeImageVisible(pbMYOBDownload, TRunning) ' Make image visible or invisible
End Sub

Iteration Not Working As Intended

I'm using a DO interation to loop a function I'm using to test for internet connectivity. The code is working fine, except that when one of the tests is satisfied the loop stops. I want this to continue in the background while the program is running. How can I get this to work?
Private Sub checkInternet()
Dim InetChecker As Boolean
InetChecker = CheckForInternetConnection()
Do While LabelCount.Text <> ""
Thread.Sleep(10)
If InetChecker = True Then
Dim image = My.Resources.greenbar
PictureBox4.Image = image
Else
Thread.Sleep(10)
Dim image = My.Resources.redbar
PictureBox4.Image = image
'NoInetConnError.Show()
End If
Loop
End Sub
Your assistance would be greatly appreciated, thanks.
Put a BackgroundWorker on your form (you will find it in the Components section of the Toolbox).
In the Properties window set WorkerReportsProgress to True for your BackgroundWorker.
Insert the following code to your form
Private connected As Boolean
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
Handles BackgroundWorker1.DoWork
While True
Dim online = CheckForInternetConnection()
If online <> connected Then
connected = online
BackgroundWorker1.ReportProgress(CInt(online))
End If
Thread.Sleep(500)
End While
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) _
Handles BackgroundWorker1.ProgressChanged
Dim online As Boolean = CBool(e.ProgressPercentage)
If online Then
PictureBox4.Image = My.Resources.greenbar
Else
PictureBox4.Image = My.Resources.redbar
End If
End Sub
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
' Start the background worker
BackgroundWorker1.RunWorkerAsync()
End Sub
Note that Sub BackgroundWorker1_DoWork runs on a separate thread and does not freeze your form while it is running.
It would be best to do something like this in a Timer and not in a loop.
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
If CheckForInternetConnection Then
PictureBox4.Image = My.Resources.greenbar
Else
PictureBox4.Image = My.Resources.redbar
End If
End Sub
If you have access to .Net framework 3+ then you could use the DispatcherTimer class which essentially creates an interval (set at whatever length you require) which you can handle the tick event for. When the tick event is raised, you can do your internet connection check.
Modifying the MSDN example for your situation, you could do something like this:
' DispatcherTimer setup
dispatcherTimer = New Threading.DispatcherTimer()
AddHandler dispatcherTimer.Tick, AddressOf dispatcherTimer_Tick
dispatcherTimer.Interval = New TimeSpan(0,0,1) ' Or however long you want
dispatcherTimer.Start()
Private Sub dispatcherTimer_Tick(ByVal sender As Object, ByVal e As EventArgs)
' Checks to see whether an internet connection is still available etc
checkInternet()
' Forcing the CommandManager to raise the RequerySuggested event
CommandManager.InvalidateRequerySuggested()
End Sub

VB.Net Asynchronous background worker inside a loop

Im using Vb.net visual studio 2008. i have got a process(system.diagnostics.process) to be run in background and it updates the Ui thread progressbar and a label and i have worked it using backgroundworker.runworkerAsync. Now the problem is i have to work the same process for a number of time with different inputs.
The code block is :
Private Sub fnStartEvent(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.click
Dim inputFolder = Directory.GetFiles(textboxSourceFolder.text)
Dim currentNumberOfFile As Integer=1
For each Files in inputFolder
Dim arguments As Object = Files
updateProgressStatus(0, currentNumberOfFile)
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync(New Object() {arguments})
currentNumberOfFile += 1
Next
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'uses the arguments
Dim Bg_process As System.Diagnostics.Process = New System.Diagnostics.Process
With Bg_process.StartInfo
.Arguments = str_arguments
.FileName = ffmpegPath
.CreateNoWindow = True
.UseShellExecute = False
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
Bg_process.Start()
Dim outputReader As StreamReader = Bg_process.StandardError
Dim output As String
While Not Bg_process.HasExited
output = outputReader.ReadLine()
BackgroundWorker1.ReportProgress(0, output)
Threading.Thread.Sleep(500)
End While
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
' process args
updateProgressStatus(args(0), args(1) )
End Sub
Private Function BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Messagebox.Show(e.error.ToString)
End Try
Sub updateProgressStatus(ByVal progressValue As Integer, ByVal progressStatus As String)
progressBar.value = progressValue
lblprogressStatus.Text = progressStatus
End Sub
The problem in here is the fnStartEvent method once gets started, it calls BackgroundWorker1.runWorkerAsync process and that runs in a seperate thread and does not wait for the thread to complete and it moves to the next line of code i.e loops to the next item and it returns to same BackgroundWorker1.runWorkerAsync line and throws exception that it is already running.
Tried
1.
Private Sub fnStartEvent(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.click
Dim inputFolder = Directory.GetFiles(textboxSourceFolder.text)
Dim currentNumberOfFile As Integer=1
For each Files in inputFolder
Dim arguments As Object = Files
updateProgressStatus(0, currentNumberOfFile)
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync(New Object() {arguments})
''
Do Until BackgroundWorker1.IsBusy
Thread.Sleep(500)
Loop
currentNumberOfFile += 1
Next
End Sub
But this does not updates the Ui thread used to denote progress.
2.Put the whole process inside the DoWork thread and loop for each file in there itself, but that to returns the cross thread error in progress bar updation.
what is the standard procedure in executing a loop for the backgroundworker to wait for finishing as well as update the UI without blocking it.
Whenever you use Thread.Sleep, you are actually sleeping the current thread that is hooked to your startup class (ie. Form). So, if you sleep your main thread, no UI updates will happen.
Per the MSDN article regarding BackgroundWorker.IsBusy, you need to throw an Application.DoEvents. Code below is copied from the article linked above.
Private Sub downloadButton_Click( _
ByVal sender As Object, _
ByVal e As EventArgs) _
Handles downloadButton.Click
' Start the download operation in the background.
Me.backgroundWorker1.RunWorkerAsync()
' Disable the button for the duration of the download.
Me.downloadButton.Enabled = False
' Once you have started the background thread you
' can exit the handler and the application will
' wait until the RunWorkerCompleted event is raised.
' If you want to do something else in the main thread,
' such as update a progress bar, you can do so in a loop
' while checking IsBusy to see if the background task is
' still running.
While Me.backgroundWorker1.IsBusy
progressBar1.Increment(1)
' Keep UI messages moving, so the form remains
' responsive during the asynchronous operation.
Application.DoEvents()
End While
End Sub