我在尝试让后台工作人员正常工作以填充几个TreeView节点时遇到很多麻烦。在所说的TreeView中,我有多个级别的节点。例如
模型是指MicroStation模型(CAD绘图程序),最简单的解释方法是电子表格中的图纸。
我正在使用FileDialog来选择文件,一旦选择了文件,则每个文件名都会使用其自己的Node添加到TreeView中。
这个想法是程序将打开每个文件,扫描每个模型,并在文件Node下的带有测试类型和结果的子TreeNode中添加子。
后台工作程序的DoWork功能如下。我已经删除了很多代码,只是我的帖子。但是程序有7个“测试”,我已经包含了2个。 在下面的示例中,“ CheckFonts”是一个仅计算文件中文本元素并返回数字的函数。
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For i As Integer = 0 To m_CountTo
If BackgroundWorker1.CancellationPending Then
e.Cancel = True ' Set Cancel to True
Exit For
End If
Dim sError As String = ""
Dim bBorderFound As Boolean = False
Dim oDesignFile As DesignFile
Dim oModel As ModelReference
Dim oFontNode As New TreeNode
Dim oFontResultNode As New TreeNode
For Each oNode As TreeNode In trvItems.Nodes
Dim ustn As New MicroStationDGN.Application
oDesignFile = ustn.OpenDesignFileForProgram(oNode.Text, True)
For Each oModel In oDesignFile.Models
'####### Checks for Items on Default Level #######
If bDefaultPass = True Then
Dim iDefaultItems As Long
iDefaultItems = DefaultItems(oModel)
If iDefaultItems > 0 Then
sDefaultMessage = "There are " & iDefaultItems & " items on the Default Level"
bDefaultPass = False
Else
sDefaultMessage = "There are no items on the Default Level"
bDefaultPass = True
End If
End If
'####### Checks for Non Standard Fonts #######
If bFontPass = True Then
Dim iFontCheck As Long
iFontCheck = CheckFonts(oModel)
If iFontCheck > 0 Then
sFontMessage = "There are " & iFontCheck & " Text Elements that use a Non Standard Font."
bFontPass = False
ElseIf iFontCheck = -99999 Then
sFontMessage = "There are some corrupt or invalid Fonts used in the Design File"
bFontPass = False
Else
sFontMessage = "All Text Elements use the Correct Font"
bFontPass = True
End If
End If
Next ' End Model
oFontNode = oNode.Nodes.Add("Font Check")
oFontResultNode = oFontNode.Nodes.Add("")
If bFontPass = True Then
oFontResultNode.Text = "PASS - " & sFontMessage
oFontResultNode.ImageIndex = 0
oNode.Collapse()
Else
oFontResultNode.Text = "FAIL - " & sFontMessage
bPass = False
oFontResultNode.ImageIndex = 1
oFontNode.ImageIndex = 1
oNode.Expand()
oFontNode.Expand()
End If
oDefaultItemsNode = oNode.Nodes.Add("Default Items Check")
oDefaultItemsResultNode = oDefaultItemsNode.Nodes.Add("")
If bDefaultPass = True Then
oDefaultItemsResultNode.Text = "PASS - " & sDefaultMessage
oDefaultItemsResultNode.ImageIndex = 0
oNode.Collapse()
Else
oDefaultItemsResultNode.Text = "FAIL - " & sDefaultMessage
oDefaultItemsResultNode.ImageIndex = 1
oDefaultItemsResultNode.ImageIndex = 1
oNode.Expand()
bPass = False
End If
Next ' End File
Next
End Sub
我以前曾与Background Workers一起工作过,但这比我所做的要复杂一些,我知道您不能从其他线程更新控件,并且Invoke用于传递信息。但是我很困惑如何使用多个节点。我看到的最好的例子是在这里
Adding nodes to treeview with Begin Invoke / Invoke
但是有多个节点,代码变得很混乱,无法正常工作。关于调用Invoke / BeginInvoke的错误消息不断出现。
所以,我想我的主要问题是我应该在哪里调用Invoke命令以最好地利用后台工作程序?
提前谢谢!