我是靠谱客的博主 冷艳乐曲,这篇文章主要介绍VB.NET读取数据库时多线程显示进度条,现在分享给大家,希望可以做个参考。

VB.net通过ADO.NET连接数据库,或执行查询语句等,都需要等待一段时间,这段时间界面无法操作,程序显示出假死现象,无任何响应,为了不让用户误认为电脑死机,需要显示一个进度条来提示用户。但是问题在于,ADO.NET(包括其它数据库引擎)在执行指令时并不返回实时状态信息,只有在命令执行完毕后,才返回结果。因此,需要通过VB.NET多线程技术,在ADO.NET执行命令期间,显示一个不断变化的进度条,这个进度条是一个单独窗口:
这里写图片描述
窗体命名为TaskProgress,放置一个ProgressBar控件命名为ProgressIndicator,代码如下:

复制代码
1
2
3
4
5
6
7
8
Public Class TaskProgress Private Sub TaskProgress_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ProgressIndicator.Maximum = 100 ProgressIndicator.Minimum = 0 ProgressIndicator.MarqueeAnimationSpeed = 30 ProgressIndicator.Style = ProgressBarStyle.Marquee End Sub End Class

主窗口增加BackgroundWorker组件,此类组件就是用于多线程编程应用的,将其WorkerSupportsCancellation属性设为真(TRUE),这个属性决定组件是否响应主线程的中断,如图:
这里写图片描述
属性设置:
这里写图片描述
代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#Region "---------------再开一个线程显示进度条---------------" Private Sub waitstart() Me.Cursor = Cursors.WaitCursor '光标为沙漏 BackgroundWorker1.RunWorkerAsync() '开启多线程显示进度条 End Sub Private Sub waitend() BackgroundWorker1.CancelAsync() '停止多线程 Me.Cursor = Cursors.Default '光标为箭头 End Sub Private Sub BackgroundWorker1_DoWork1(sender As Object, _ e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork Dim worker As System.ComponentModel.BackgroundWorker = _ CType(sender, System.ComponentModel.BackgroundWorker) ' Assign the result of the computation ' to the Result property of the DoWorkEventArgs ' object. This is will be available to the ' RunWorkerCompleted eventhandler. showProgress(worker) End Sub Private Sub showProgress(ByVal worker As System.ComponentModel.BackgroundWorker) Dim progressForm As New TaskProgress() progressForm.Show() ' Refresh causes an instant (non-posted) display of the label. progressForm.Refresh() ' Slowly increment the progress bar. While Not worker.CancellationPending If progressForm.ProgressIndicator.Value = 100 Then progressForm.ProgressIndicator.Value = 0 Else progressForm.ProgressIndicator.Value += 10 End If ' 50 millisecond delay System.Threading.Thread.Sleep(50) End While progressForm.ProgressIndicator.MarqueeAnimationSpeed = 0 ' Remove the form after the "task" finishes. progressForm.Hide() progressForm.Dispose() End Sub #End Region

打开数据库之前,先使用 waitstart 过程显示进度条,数据库读取完毕,再用 waitend 停止显示,返回界面。

最后

以上就是冷艳乐曲最近收集整理的关于VB.NET读取数据库时多线程显示进度条的全部内容,更多相关VB内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部