Here is an exerpt from an article I'm writing.... When I'm done, I raise
FillIt (Ignore the FillComplete, that's actually what I'm going to
ultimately use) Fillit is being hanlded by Notify...This isn't the best
example, but it should get you through what you want. Remember though,
please remember, Forms aren't thread safe!!!!!!!!! I've dropped the ball on
that a few times...
Now, declare some module level variables:
Const cs As String = "data source=----;initial catalog=--;integrated
security=SSPI "
Dim SqlDataAdapter1 As New System.Data.SqlClient.SqlDataAdapter
Dim dt As New DataTable
Dim cn As New SqlConnection(cs)
Now, here's the code that fires the query:
Dim th As Thread 'Declare a new Thread
Dim asy As New AsynchGrid 'AsnychGrid is the Class we are going to use
asy.PatientDataAdapter = SqlDataAdapter1 '
Dim cmd As New SqlCommand("SELECT * FROM Where Created_Time > GetDate()-30",
cn)
SqlDataAdapter1.SelectCommand = cmd
asy.PatientDataSet = dt
Label1.Text = "Starting"
AddHandler asy.FillIt, AddressOf Notify
Dim tsFill As ThreadStart = New ThreadStart (AddressOf asy.FillPatient)
th = New Thread(tsFill)
th.Name = "Filler Thread"
th.Start()
Now, understand what we want to accomplish. We want to fire a query and
then give control back to the user. Whenever the query is returned, we'll
notify the caller that it's done and then do whatever we need to with the
query results. But we want the user to be able to do other things while
this is happening. So, Notify is a Subroutine that I have that will fill a
ListBox control with some of the data from the query. This snippet really
doesn't matter, we could do just about anything here.I just chose this for
the sake of illustration:
Private Sub Notify()
Dim dr As DataRow
ListBox1.Items.Clear()
ListBox1.BeginUpdate()'This will speed up the ListBox Fill
For Each dr In dt.Rows
ListBox1.Items.Add(dr(1).ToString)
Next
ListBox1.EndUpdate() 'We're done filling it so we can end it
End Sub
Now, I have a class called AysnchGrid (I was initially binding to a
DataGrid.sorry about the counterintuitive name) that has the following
private members:
Private _dtPatient As DataTable
Private _daPatient As SqlDataAdapter
Private m_cn As SqlConnection
Public Event FillComplete()
Public Event FillIt()
Now, in a Method I call FillPatient is the actual guts of the process:
Try
_dtPatient.Clear()
_daPatient.Fill(_dtPatient)
RaiseEvent FillIt()
Catch excFill As SqlClient.SqlException
Console.WriteLine(excFill.Message)
End Try