每次迭代VB.Net WPF后更新文本框
我有一个For循环,它通过目录中的xlsx文件运行,我需要在每个循环之后将文件名附加到TextBlock中,并刷新TextBlock以显示更新的文本 下面的代码只显示循环执行后的文件名每次迭代VB.Net WPF后更新文本框,wpf,vb.net,for-loop,Wpf,Vb.net,For Loop,我有一个For循环,它通过目录中的xlsx文件运行,我需要在每个循环之后将文件名附加到TextBlock中,并刷新TextBlock以显示更新的文本 下面的代码只显示循环执行后的文件名 Dim lcFileName As String = "" Dim fileArray() As String = Directory.GetFiles(txtDirectory.Text, "*.xlsx", SearchOption.AllDirectories) For Each file A
Dim lcFileName As String = ""
Dim fileArray() As String = Directory.GetFiles(txtDirectory.Text, "*.xlsx", SearchOption.AllDirectories)
For Each file As String In fileArray
Dim ExcelApp As Excel.Application = New Excel.Application
Dim Workbook As Excel.Workbook = ExcelApp.Workbooks.Open(file)
Dim Worksheet As Excel.Worksheet = Workbook.Sheets(1)
Dim Range As Excel.Range = Worksheet.UsedRange
Dim rowCount As Integer = Range.Rows.Count
Dim colCount As Integer = Range.Columns.Count
Dim tmpOrder(rowCount, colCount) As String
tbResults.Text = tbResults.Text + Environment.NewLine + Path.GetFileName(file) + " imported."
For i = 1 To rowCount
For j = 1 To colCount
'New line
If (i = 1 And j = 1) Then
tmpOrder(i - 1, j - 1) = Range.Cells(i, j).Value
lcFileName = tmpOrder(i - 1, j - 1).ToString()
Else
If (Not String.IsNullOrEmpty(Range.Cells(i, j).Value)) Then
tmpOrder(i - 1, j - 1) = Range.Cells(i, j).Value.ToString()
End If
End If
Next
Next
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Worksheet)
Worksheet = Nothing
ExcelApp.ActiveWorkbook.Close(True)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Workbook)
Workbook = Nothing
ExcelApp.Quit()
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExcelApp)
ExcelApp = Nothing
'
Next
如果需要VB.Net帮助,我们将不胜感激。有些东西不太好,正在阻止表单更新 通过在其中一个循环中添加Application.DoEvents(),可以允许应用程序处理挂起的显示操作 这涉及到一些开销,因此您可能希望它在外循环中,而不是在内循环中。终于让它工作了。 确定首先,我创建了一个方法,用传递给文件名的参数更新TextBlock
Public Sub UpdateResults(ByVal lcFile As String)
tbResults.Text = tbResults.Text + Environment.NewLine + Path.GetFileName(lcFile) + " imported."
End Sub
在For循环中,我使用以下代码调用了该方法
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, New ThreadStart(Sub() Me.UpdateResults(lcFile)))
其中UpdateResults(lcFile)是传递的方法和参数
如果不传递任何参数,则使用此函数调用方法,其中“MyMethod”是要运行的方法的名称
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, New ThreadStart(AddressOf MyMethod))
您需要以异步模式执行此操作,因为您在计算时无法刷新UI。@scharette如果不太麻烦,您能否提供一个示例?thanks@scharette因此,在快速查看之后,我使用了async,但是在执行时,我得到了错误“调用线程无法访问此对象,因为它是另一个线程拥有的。”有什么建议吗?谢谢顺便看一看,您可以通过使用Excel的一个实例而不是重复创建一个新实例并退出它来提高速度。我尝试过Application.DoEvents(),但效果很差,它更新了文本块两次,然后跳过了几个,而不是一个接一个。还有其他建议吗?谢谢它并不能保证显示每一个变化,它只是为了让UI“跟上”。除非您想在不同的线程上运行程序逻辑和屏幕更新,否则这是您将要做的最好的事情。@TerryCarmen请查看的答案。为什么?我没有问题。不需要编辑问题的标题来表示问题已解决,只需单击相应答案上的“接受”(可能是您发布的答案)。