Search code examples
.netvb.netbackgroundworkermdi

BackgroundWorker in MDI app


I am trying to use the BackgroundWorker in my MDI application to handle the process of uploading a file to FTP server and displaying the progress on a progress bar.

When I tried to do it on a separate proof-of-concept application with a simple window and one button - it worked OK. But when I am trying to do it in my real app - the doWork sub does not run. Instead of it the app immediately runs the RunWorkerCompleted sub and shows me "Upload complete" without doing the actual job.

Is there something about MDI that prevents the BackgroundWorker to run the same way as with regular window app?

Thanks in advance for your help

Code:

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    bWorker.RunWorkerAsync()

End Sub

Private Sub bWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bWorker.DoWork

    Dim source = Application.StartupPath + "\Db\test.mdb"
    Dim NameToUpload As String = Path.GetFileName(source)

    NameToUpload = NameToUpload.Replace(".", DateTime.Now.ToShortTimeString() + ".")

    Dim request As FtpWebRequest = DirectCast(WebRequest.Create(Host + "/" + txtLogin.Text + "/" + NameToUpload), FtpWebRequest)
    request.Method = WebRequestMethods.Ftp.UploadFile
    request.Credentials = New NetworkCredential(txtLogin.Text, txtPassword.Text)
    Dim FileStream() As Byte = File.ReadAllBytes(source)
    Dim requestStream As System.IO.Stream = request.GetRequestStream()

    For offset As Integer = 0 To FileStream.Length Step 1024
        bWorker.ReportProgress(CType(offset * ProgressBar1.Maximum / FileStream.Length, Integer))
        Dim chSize As Integer = FileStream.Length - offset
        If chSize > 1024 Then chSize = 1024
        requestStream.Write(FileStream, offset, chSize)
    Next
    requestStream.Close()
    requestStream.Dispose()
End Sub

Private Sub bWorker_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs)
    ProgressBar1.Value = e.ProgressPercentage

End Sub

Private Sub bWorker_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs)
    MsgBox("Upload complete")
End Sub

Solution

  • You need to check e.Error in the RunWorkerCompleted event as it's most likely having an exception. As @Zaggler mentions you're accessing UI controls on the background thread which will cause this.