BackgroundWork,SQL查询和冻结表单

时间:2016-04-12 20:00:26

标签: sql-server vb.net datagridview

我尝试使用BackgroudWorker将数据加载到DataTable中,然后将其返回到DataGridView。

Public Sub Reload_Selected_Invoice()
    bgwLoadOldInvoices.RunWorkerAsync()
End Sub

Private Sub bgwLoadOldInvoices_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgwLoadOldInvoices.DoWork
    Dim DataTable As New DataTable
    Using SQLSERVER_Connection As New SqlConnection("Server = localhost;Database=test;Integrated Security=SSPI;")
        Using SQLQuery As New SqlCommand("SQLQuery that takes a few seconds;", SQLSERVER_Connection)
            SQLSERVER_Connection.Open()
            Using SqlDataAdapter As New SqlDataAdapter(SQLQuery)
                SqlDataAdapter.Fill(DataTable)
            End Using
            SQLSERVER_Connection.Close()
        End Using
    End Using
    e.Result = DataTable
End Sub

Private Sub bgwLoadOldInvoices_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bgwLoadOldInvoices.RunWorkerCompleted
    dgvOldInvoices.DataSource = e.Result
End Sub

当我按下按钮时,表单停止响应,直到查询完成。这是我对线程的第一次尝试,我不知道我在哪里弄乱。

修改1

Private Sub bgwLoadOldInvoices_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgwLoadOldInvoices.DoWork
    Dim DataGridView1 As New DataGridView
    Dim DataTable As New DataTable
    Using SQLSERVER_Connection As New SqlConnection("Server = localhost;Database=test;Integrated Security=SSPI;")
        Using SQLQuery As New SqlCommand("SQLQuery that takes a few seconds;", SQLSERVER_Connection)
            Using SqlDataAdapter As New SqlDataAdapter(SQLQuery)
                SqlDataAdapter.Fill(DataTable)
            End Using
        End Using
    End Using
    DataGridView1.DataSource = DataTable
    e.Result = DataGridView1
End Sub

Private Sub bgwLoadOldInvoices_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bgwLoadOldInvoices.RunWorkerCompleted
    dgvOldInvoices = DirectCast(e.Result, DataGridView)
    dgvOldInvoices.Refresh()
    MessageBox.Show("Finished!")
End Sub

0 个答案:

没有答案