如何防止UI在漫长的过程中冻结? [英] How to prevent UI from freezing during lengthy process?

查看:22
本文介绍了如何防止UI在漫长的过程中冻结?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to write a VB.Net 2008 applet to go through all the fixed-drives looking for some files. If I put the code in ButtonClick(), the UI freezes until the code is done:

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 控件的信息:这是解决此问题的正确方法/方法吗?如果没有,您会推荐什么解决方案,可能是一个非常简单的例子?

Google returned information on a BackGroundWorker control: Is this the right/way to solve this issue? If not, what solution would you recommend, possibly with a really simple example?

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

FWIW, I read that Application.DoEvents() is a left-over from VBClassic and should be avoided.

谢谢.

推荐答案

BackgroundWorker 是解决问题的好方法.实际上文档说明了这一点:

The BackgroundWorker is a good way to solve your problem. Actually the documentation states this:

BackgroundWorker 类允许您在单独的专用线程上运行操作.下载和数据库事务等耗时操作可能会导致您的用户界面 (UI) 看起来好像在它们运行时已停止响应.当您需要响应式 UI 并且面临与此类操作相关的长时间延迟时,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.

这篇关于如何防止UI在漫长的过程中冻结?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆