后台工作者的VB NET问题

时间:2018-08-14 16:20:07

标签: vb.net backgroundworker

我的后台工作者在做他的工作时,我想更改主要形式的标签,以告知当时正在执行的流程。

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

我的后台工作者

    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没有任何反应。

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

谢谢。

1 个答案:

答案 0 :(得分:5)

确保您的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