gpt4 book ai didi

vb.net - 如何防止UI在漫长的过程中卡住?

转载 作者:行者123 更新时间:2023-12-02 06:30:09 24 4
gpt4 key购买 nike

我需要编写一个 VB.Net 2008 小程序来遍历所有固定驱动器以查找一些文件。如果我将代码放入 ButtonClick() 中,UI 将卡住,直到代码完成:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'TODO Find way to avoid freezing UI while scanning fixed drives

Dim drive As DriveInfo
Dim filelist As Collections.ObjectModel.ReadOnlyCollection(Of String)
Dim filepath As String

For Each drive In DriveInfo.GetDrives()
If drive.DriveType = DriveType.Fixed Then
filelist = My.Computer.FileSystem.GetFiles(drive.ToString, FileIO.SearchOption.SearchAllSubDirectories, "MyFiles.*")
For Each filepath In filelist
'Do stuff
Next filepath
End If
Next drive
End Sub

Google 返回了有关 BackGroundWorker 控件的信息:这是解决此问题的正确/方法吗?如果没有,您会推荐什么解决方案,可能是一个非常简单的示例?

FWIW,我读到 Application.DoEvents() 是 VBClassic 的遗留物,应该避免。

谢谢。

最佳答案

BackgroundWorker是解决您问题的好方法。实际上文档是这么说的:

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

关于vb.net - 如何防止UI在漫长的过程中卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2447123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com