jvcoach23
Centurion
I've been doing some research on Threading and am trying to give it a go. In my sample code, i have everything working except the return values are not getting passed back to the parent thread to be displayed in the list box. the debug.writeline tells me I'm getting the database back.. but can't get it to the parent thread. what am I doing wrong.
Visual Basic:
Option Strict Off
Imports System.Threading
Imports System.Data
Imports System.Data.SqlClient
Public Class Form3
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Dim t1 As Thread
Dim t2 As Thread
Dim WithEvents oSquare As SquareClass
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim oSquare1 As New SquareClass
Dim oSquare2 As New SquareClass
t1 = New Thread(AddressOf oSquare1.CalcSquare)
t1.Name = "Data"
oSquare1.vcTableName = "tblPMData"
t2 = New Thread(AddressOf oSquare2.CalcSquare)
t2.Name = "Company"
oSquare2.vcTableName = "tblPMCompany"
t1.Start()
t2.Start()
If t1.Join(500) Then
Me.ListBox1.Items.Add(oSquare1.Result)
End If
If t2.Join(500) Then
Me.ListBox2.Items.Add(oSquare2.Result)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
t1.Abort()
End Sub
Public Class SquareClass
Private mvalue As Integer
Private msquare As Double
Private mvcTableName As String
Private mresult As Integer
Public Event threadcomplete(ByVal Result As Integer)
Public Property vcTableName() As String
Get
Return mvcTableName
End Get
Set(ByVal pValue As String)
mvcTableName = pValue
End Set
End Property
Public Property Result() As Integer
Get
Return mresult
End Get
Set(ByVal pValue As Integer)
mresult = pValue
End Set
End Property
Public Property value1() As Integer
Get
Return mvalue
End Get
Set(ByVal pValue As Integer)
mvalue = pValue
End Set
End Property
Public Property square() As Double
Get
Return (msquare)
End Get
Set(ByVal pSquare As Double)
msquare = pSquare
End Set
End Property
Public Sub CalcSquare()
SyncLock GetType(SquareClass)
Dim cn As SqlConnection
Dim cm As New SqlCommand
Dim result As Integer
cn = New SqlConnection("pwd=idontusesa; UID=sa; server=Ntdts1; database=Monitor")
cm = New SqlCommand
With cm
.Connection = cn
.CommandType = CommandType.Text
.CommandText = "select count(1) from " & vcTableName
End With
cn.Open()
Try
result = cm.ExecuteScalar
Catch ex As Exception
Throw ex
End Try
cn.Close()
Debug.WriteLine(result)
'MsgBox(vcTableName & " had " & CType(result, String) & " rows")
RaiseEvent threadcomplete(result)
End SyncLock
End Sub
End Class
Private Sub oSquare_threadcomplete(ByVal Result As Integer) Handles oSquare.threadcomplete
MsgBox(Result)
End Sub