我在Windows窗体上有一个RichTextBox,我想用检查点'当我完成XML构建过程时。
我有一个名为' LogFiles'具有RichTextBox的委托
Public Delegate Sub AppendRichTextBoxDelegate(ByVal RTB As RichTextBox, ByVal txt As String)
在那个班级中,我有附加RTB的子
Public Shared Sub AppendRichTextBox(ByVal RTB As RichTextBox, ByVal txt As String)
Try
If RTB.InvokeRequired Then
RTB.Invoke(New AppendRichTextBoxDelegate(AddressOf AppendRichTextBox), New Object() {RTB, txt})
Else
RTB.AppendText(txt & Environment.NewLine)
End If
Catch ex As Exception
MsgBox(MsgBox(ex.Message & Environment.NewLine & Environment.NewLine & ex.StackTrace))
End Try
End Sub
现在我打电话给BackGroundWorker
Public Sub BGW1ProcessFile_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BGW1ProcessFile.DoWork
LogFiles.AppendRichTextBox(LogFileRTB, "Starting")
LogFiles.CreateLog()
Interchange.StartXML()
End Sub
AppendRichTextBox按预期工作并实时更新RTB,但是当我停止进入Interchange.StartXML'它还包含一个AppendRichTextBox,它不会从该Sub中更新RTB。
当BackGroundWorker完成AppendRichTextBox以使RunWorkerCompleted事件按预期工作时。
为什么我使用委托创建的AppendRichTextBox Sub在BackGroundWorker流程上工作,但对作为BackGroundWorker流程的一部分启动的Sub不起作用?
它的酸洗了一下,任何帮助都会受到赞赏。
此致
詹姆斯
答案 0 :(得分:1)
正如通过注释所解释的那样,BackgroundWorker
正是为了处理涉及GUI +另一个线程的2线程情况。这就是为什么它内置的功能可以优雅地解释最可能的情况。
在您的情况下(即,定期更新BGW线程中的GUI元素),您应该依赖ProgressChanged
事件。在这里,您有一个示例代码,清楚地显示了如何使用它:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BGW1ProcessFile.WorkerReportsProgress = True
BGW1ProcessFile.RunWorkerAsync()
End Sub
Private Sub BGW1ProcessFile_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BGW1ProcessFile.ProgressChanged
'You can include here as complex modifications on the GUI as
'required. Just store anything in e.UserState, as shown below
RTB.Text = RTB.Text & e.UserState.ToString & Environment.NewLine
End Sub
Private Sub modifyRTB(caseNo As Integer)
'Here you are calling the aforementioned ProgressChanged event.
BGW1ProcessFile.ReportProgress(0, "This is case " & caseNo.ToString)
End Sub
Private Sub BGW1ProcessFile_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BGW1ProcessFile.DoWork
BGW1ProcessFile.ReportProgress(0, "We are in the BGW thread now")
modifyRTB(1)
modifyRTB(2)
modifyRTB(3)
End Sub
Private Sub BGW1ProcessFile_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGW1ProcessFile.RunWorkerCompleted
RTB.Text = RTB.Text & Environment.NewLine & "We are outside the BWG thread now"
End Sub