避免在 vb.net 中实时更新文本框
Avoid updating textbox in real time in vb.net
我在 VB.NET 程序中有一个非常简单的代码,用于在文本框中加载文件夹中的所有路径。代码运行良好,问题是它实时添加行,因此在界面逐行显示时加载 20k 文件大约需要 3 分钟。
这是我的代码:
Dim ImageryDB As String() = IO.Directory.GetFiles("c:\myimages\")
For Each image In ImageryDB
txtbAllimg.AppendText(image & vbCrLf)
Next
如何强制我的程序分块加载文件或每秒更新界面?
提前致谢
是的,你可以做到。您需要将文件名加载到某种离屏数据结构中,而不是将它们直接加载到控件中。然后您可以定期更新控件以显示到目前为止加载的任何内容。但是,我认为您会发现 仅 更新控件会导致速度变慢。一旦删除该部分,就无需在加载过程中定期更新控件,因为它几乎是瞬时的。
您可以将所有文件名加载到一个字符串中,然后在完全加载后才将文本框设置为该字符串,如下所示:
Dim imagePaths As String = ""
For Each image As String In Directory.GetFiles("c:\myimages\")
imagePaths &= image & Environment.NewLine
Next
txtbAllimg.Text = imagePaths
但是,这不如使用 StringBuilder
:
Dim imagePaths As New StringBuilder()
For Each image As String In Directory.GetFiles("c:\myimages\")
imagePaths.AppendLine(image)
Next
txtbAllimg.Text = imagePaths.ToString()
但是,由于 GetFiles
方法已经将完整的路径列表作为字符串数组返回给您,因此仅使用 String.Join
方法将数组中的所有项目组合成一个字符串:
txtbAllimg.Text = String.Join(Environment.NewLine, Directory.GetFiles("c:\myimages\"))
我知道这不是您实际问题的答案,但 AppendText 很慢。使用 ListBox 并将项目添加到它大约是。快 3 倍。 ListBox 的另一个好处是能够 select 轻松地选择一个项目(至少比 TextBox 更容易)
For each image in ImageryDB
Me.ListBox1.Items.add (image)
Next
但是,可能还有一种更有用、更快捷的方法来执行此操作。使用文件信息。
Dim dir As New IO.DirectoryInfo("C:\myImages")
Dim fileInfoArray As IO.FileInfo() = dir.GetFiles()
Dim fileInfo As IO.FileInfo
For Each fileInfo In fileInfoArray
Me.ListBox2.Items.Add(fileInfo.Name)
Next
我在 VB.NET 程序中有一个非常简单的代码,用于在文本框中加载文件夹中的所有路径。代码运行良好,问题是它实时添加行,因此在界面逐行显示时加载 20k 文件大约需要 3 分钟。
这是我的代码:
Dim ImageryDB As String() = IO.Directory.GetFiles("c:\myimages\")
For Each image In ImageryDB
txtbAllimg.AppendText(image & vbCrLf)
Next
如何强制我的程序分块加载文件或每秒更新界面?
提前致谢
是的,你可以做到。您需要将文件名加载到某种离屏数据结构中,而不是将它们直接加载到控件中。然后您可以定期更新控件以显示到目前为止加载的任何内容。但是,我认为您会发现 仅 更新控件会导致速度变慢。一旦删除该部分,就无需在加载过程中定期更新控件,因为它几乎是瞬时的。
您可以将所有文件名加载到一个字符串中,然后在完全加载后才将文本框设置为该字符串,如下所示:
Dim imagePaths As String = ""
For Each image As String In Directory.GetFiles("c:\myimages\")
imagePaths &= image & Environment.NewLine
Next
txtbAllimg.Text = imagePaths
但是,这不如使用 StringBuilder
:
Dim imagePaths As New StringBuilder()
For Each image As String In Directory.GetFiles("c:\myimages\")
imagePaths.AppendLine(image)
Next
txtbAllimg.Text = imagePaths.ToString()
但是,由于 GetFiles
方法已经将完整的路径列表作为字符串数组返回给您,因此仅使用 String.Join
方法将数组中的所有项目组合成一个字符串:
txtbAllimg.Text = String.Join(Environment.NewLine, Directory.GetFiles("c:\myimages\"))
我知道这不是您实际问题的答案,但 AppendText 很慢。使用 ListBox 并将项目添加到它大约是。快 3 倍。 ListBox 的另一个好处是能够 select 轻松地选择一个项目(至少比 TextBox 更容易)
For each image in ImageryDB
Me.ListBox1.Items.add (image)
Next
但是,可能还有一种更有用、更快捷的方法来执行此操作。使用文件信息。
Dim dir As New IO.DirectoryInfo("C:\myImages")
Dim fileInfoArray As IO.FileInfo() = dir.GetFiles()
Dim fileInfo As IO.FileInfo
For Each fileInfo In fileInfoArray
Me.ListBox2.Items.Add(fileInfo.Name)
Next