如何在执行大SQLCommand VB.Net时显示进度条

前端之家收集整理的这篇文章主要介绍了如何在执行大SQLCommand VB.Net时显示进度条前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个大的sql命令,通常返回20 000 – 100 000行数据.
但是只要我调用executeMyQuery函数,程序就会挂起几秒钟,具体取决于返回的大小.

我只返回一列.

如何在运行此命令时显示进度条?

也许在线程或其他东西(我没有线程经验)

这是我的代码(参数是从3个不同的comboBox.selectedItem发送的):

Public Function executeMyQuery(dbname As String,colname As String,tblname As String)
    Try
        ListBox1.Items.Clear()
        If Not String.IsNullOrWhiteSpace(connString) Then
            Using cn As sqlConnection = New sqlConnection(connString)
                cn.Open()
                Using cmd As sqlCommand = New sqlCommand()
                    cmd.Connection = cn
                    Dim qry As String
                    qry = String.Format("select distinct [{0}] from {1}.dbo.{2} where [{0}] is not null",colname,dbname,tblname)
                    cmd.CommandText = qry
                    cmd.CommandTimeout = 0

                    Dim count As Integer
                    Using myReader As sqlDataReader = cmd.ExecuteReader()
                        While (myReader.Read())
                            count += 1
                            ListBox1.Items.Add(count.ToString & ". " & myReader.GetString(0))
                        End While
                    End Using
                End Using
            End Using
        End If
         cn.Close()
    Catch ex As Exception
        MsgBox("Error Occured : " & ex.Message)
        cn.Close()
    End 
End Function
这是一个如何使用VB.Net 4.0进行Asychrounous工作的简要示例.

让我们假设您有一个具有以下导入的表单,

Imports System.Windows.Forms
Imports System.Threading
Imports System.Threading.Tasks

该表格有两个控件

Private WithEvents DoSomthing As Button
Private WithEvents Progress As ProgressBar

在你的应用程序的某个地方我们有一个名为ExecuteSlowStuff的函数,这个函数相当于你的executeMyQuery.重要的部分是Action参数,该函数用于显示它正在取得进展.

Private Shared Function ExecuteSlowStuff(ByVal progress As Action) As Integer
    Dim result = 0
    For i = 0 To 10000
        result += i
        Thread.Sleep(500)
        progress()
    Next

    Return result
End Function

让我们说这项工作是通过点击DoSomething按钮开始的.

Private Sub Start() Handled DoSomething.Click
    Dim slowStuff = Task(Of Integer).Factory.StartNew(
        Function() ExceuteSlowStuff(AddressOf Me.ShowProgress))
End Sub

你可能想知道ShowProgress来自哪里,那就是更麻烦的一点.

Private Sub ShowProgress()
    If Me.Progress.Invokerequired Then
        Dim cross As new Action(AddressOf Me.ShowProgress)
        Me.Invoke(cross)
    Else 
        If Me.Progress.Value = Me.Progress.Maximum Then
            Me.Progress.Value = Me.Progress.Minimum
        Else
            Me.Progress.Increment(1)
        End If

        Me.Progress.Refresh()
    End if
End Sub

请注意,因为可以从另一个线程调用ShowProgress,它会检查跨线程调用.在这种情况下,它在主线程上调用自己.

猜你在找的VB相关文章