VB 后台工作者的 NET 问题

VB NET problems with background worker

当我的后台工作人员正在做他的工作时,我想在主窗体中更改一个标签,告诉当时正在进行什么进程。

该应用程序处理一些文件,因此我需要传递该应用程序正在处理的文件的信息。

我的后台工作者

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    If (Not System.IO.Directory.Exists(caminho & "\results")) Then
        System.IO.Directory.CreateDirectory(caminho & "\results")
    End If
    For Each folder As String In System.IO.Directory.GetDirectories(caminho)
        Dim split As String() = folder.Split("\")
        Dim parentFolder As String = split(split.Length - 1)
        If (Not System.IO.Directory.Exists(caminho & "\results" & "\" & parentFolder)) Then
            System.IO.Directory.CreateDirectory(caminho & "\results" & "\" & parentFolder)
        End If
        For Each file As String In System.IO.Directory.GetFiles(folder)
            output = file
            'Dim imgFile As System.Drawing.Image = System.Drawing.Image.FromFile(file)
            Dim thumbimage As Bitmap
            Dim originalimage As Bitmap

            Dim width As Integer = TextBox2.Text '# this is the max width of the new image
            Dim height As Integer = TextBox3.Text '# this is the max height of the new image

            originalimage = System.Drawing.Image.FromFile(file)

            thumbimage = New Bitmap(width, height)
            Dim novonome As String = Path.GetFileNameWithoutExtension(file)

            Dim gr As Graphics = Graphics.FromImage(thumbimage)
            gr.DrawImage(originalimage, 0, 0, width, height)

            thumbimage.Save(caminho & "\results" & "\" & parentFolder & "\" & novonome & ".png", Imaging.ImageFormat.Png)
            thumbimage.Dispose()
            originalimage.Dispose()
        Next
    Next
End Sub

我的进度变化:

    Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    Label3.Text = "Working file " & output
End Sub

不应该用它正在工作的文件更改 form1 中的 label3.text 吗? label3.

基本上什么都没发生

我的输出变量在 Public Class Form1 下声明。

提前致谢。

确保您的 BackgroundWorker 对象具有 WorkerReportsProgress = True

您必须在循环中调用进度:

For Each file As String In System.IO.Directory.GetFiles(folder)
  BackgroundWorker1.ReportProgress(0, file)
  ...

然后在您的 Progress 事件中,读取状态:

Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
  If e.UserState IsNot Nothing Then
    Label3.Text = "Working file " & e.UserState.ToString
  End If
End Sub