VB.NET 读取数据库时多线程显⽰进度条
VB通过ADO.NET连接数据库,或执⾏查询语句等,都需要等待⼀段时间,这段时间界⾯⽆法操作,程序显⽰出假死现象,⽆任何响应,为了不让⽤户误认为电脑死机,需要显⽰⼀个进度条来提⽰⽤户。但是问题在于,ADO.NET(包括其它数据库引擎)在执⾏指令时并不返回实时状态信息,只有在命令执⾏完毕后,才返回结果。因此,需要通过VB.NET多线程技术,在ADO.NET执⾏命令期间,显⽰⼀个不
断变化的进度条,这个进度条是⼀个单独窗⼝:
窗体命名为TaskProgress,放置⼀个ProgressBar控件命名为ProgressIndicator,代码如下:
主窗⼝增加BackgroundWorker组件,此类组件就是⽤于多线程编程应⽤的,将其WorkerSupportsCancellation属性设为真(TRUE),这
个属性决定组件是否响应主线程的中断,如图:
属性设置:
代码如下:
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
#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()
marquee marquee
' 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 = 100Then
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 停⽌显⽰,返回界⾯。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。