[RESOLVED] BackgroundWorker Help
Hey guys :D.
I have this app to copy files with a progressbar... What I'm trying to do is to set the progressbar1.maximum to the number of files in the folder.
But I'm getting a cross-thread error.
This is the error I'm getting:
Cross-thread operation not valid: Control 'ProgressBar1' accessed from another thread than the thread it was created on.
This is where I'm trying to set the ProgressBar1.Maximum:
vb.net Code:
Private Sub BackgroundWorker1_DoWork1 _
(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
ProgressBar1.Maximum = My.Computer.FileSystem.GetFiles("C:\From", FileIO.SearchOption.SearchAllSubDirectories, "*").Count
Dim i As Integer = 1
For Each file As String In My.Computer.FileSystem.GetFiles("C:\From", FileIO.SearchOption.SearchAllSubDirectories, "*")
My.Computer.FileSystem.CopyFile(file, String.Concat("E:\", Microsoft.VisualBasic.Right(file, Microsoft.VisualBasic.Len(file) - 3)), True)
worker.ReportProgress(i, i & " File(s) Copied")
i += 1
Next
End Sub
I got this code from the F1 help of VS
vb.net Code:
' Check if this method is running on a different thread
' than the thread that created the control.
If Me.textBox1.InvokeRequired Then
' It's on a different thread, so use Invoke.
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[NewText] + " (Invoke)"})
Else
' It's on the same thread, no need for Invoke.
Me.textBox1.Text = [NewText] + " (No Invoke)"
End If
How can I adjust it to my needs? What's d?
Thanks in advance :D!
Re: BackgroundWorker Help
Create a delegate type for your needs, I'll call it OneArgD. Put it after the "Class/Module name" statement in your file.
vb.net Code:
Delegate Sub OneArgD(ByVal arg As Object)
Next, you need to use Me.ProgressBar1.Invoke.
Inside your backgroundWorker event handler, where you want to set the Maximum property:
vb.net Code:
Dim deleg As New OneArgD(AddressOf SetMaximum)
Me.ProgressBar1.Invoke(deleg,My.Computer.FileSystem.GetFiles("C:\From", FileIO.SearchOption.SearchAllSubDirectories, "*").Count)
And finally, add a Private Sub declaration to your class/module...
vb.net Code:
Private Sub SetMaximum(ByVal max As Object)
Me.ProgressBar1.Maximum = CInt(max)
End Sub
I know it's really annoying to do that, but it's the only way.
Re: BackgroundWorker Help
Can you give me an example please? (I'm searching MSDN for an example too, just though yours might be clearer)
Re: BackgroundWorker Help
Sorry, I'm editing it progressively, just keep clicking Refresh to see updates.
Re: BackgroundWorker Help
Re: BackgroundWorker Help