Home .net data reader in background worker
Reply: 1

.net data reader in background worker

Pierre
1#
Pierre Published in 2017-12-07 12:06:56Z

I am trying to query a DB in a background worker in order for my form not to be frozen while the query is being processed. However since I moved to this solution, the data reader only retrieves the first result of the query instead of 400.000+ ...

Public Class Form5
    Public con As OdbcConnection = Form1.con
    Public cmd As New OdbcCommand
    Public dr As OdbcDataReader

    Dim bw As BackgroundWorker = New BackgroundWorker
    Public Delegate Sub PictureVisibilityDelegate(ByVal visibility As 
    Boolean)
    Dim ChangePictureVisibility As PictureVisibilityDelegate

    Private Sub Form5_Load(sender As Object, e As EventArgs) Handles 
        MyBase.Load
        AddHandler bw.DoWork, AddressOf bw_DoWork
        AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
        ChangePictureVisibility = AddressOf ChangeVisibility

        bw.RunWorkerAsync()

    End Sub

    Public Sub ChangeVisibility(ByVal visibility As Boolean)
        PictureLoader.Visible = visibility
        PictureLoader.SendToBack()
    End Sub

    Private Sub bw_DoWork(sender As Object, e As DoWorkEventArgs)
        Me.Invoke(ChangePictureVisibility, True)

        Dim SQL As String = "SELECT xxx, xxx, xxx from xxx.xxx where xxx.xxx      
        = """ & dt1.Rows(Form1.line).Item(4) & """"
        cmd = New OdbcCommand(SQL, con)

        dr = cmd.ExecuteReader

        While dr.Read()
           DataGridView1.Rows.Add(New String() 
           {dr(0).ToString,dr(1).ToString & " %", dr(2).ToString})
        End While

     End Sub

    Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As                 
    RunWorkerCompletedEventArgs)
        Me.Invoke(ChangePictureVisibility, False)
    End Sub

End Class

I really can't wrap my head around that and couldn't find any similar problem on the net, so any comment would be really appreciated...

jmcilhinney
2#
jmcilhinney Reply to 2017-12-07 14:09:25Z

Populate a DataTable in your DoWork event handler and assign that to e.Result. Get it back from e.Result in the RunWorkerCompleted event handler and bind it to your grid.

The DoWork event handler is where you do the background work. Anything to do with the UI is NOT background work. The RunWorkerCompleted event handler is executed on the UI thread, so that's where you update the UI once the background work is done.

In the DoWork event handler:

Dim table As New DataTable

table.Load(dr)
e.Result = table

In the RunWorkerCompleted event handler:

DataGridView1.DataSource = e.Result
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314441 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO