Quick 500 - Need help on Threading; a nice puzzle for you guru's :)
Posted on 2005-03-31
I'm been working on a CommandButton UserControl that is passed a stored procedure. When a button is pressed, It calls the Results from the database and then displays the information in a seperate form which is then aligned to the UserControl.
This is all working until today when i decided that i wanted the Database call which takes a few seconds to be done in a seperate thread... Everything is working fine, but by the time the Call finishes the forms are flashing visible then disappearing.
I've tracked the point in which the forms disappear, there are no dispose calls being made or anything like that, unfortunatly this is where it gets interesting... the Forms are disappearing when the cursor ends a subroutine.
I've made a simple peice of code for you guys to compile
You need to breakpoint the 'End Sub' which i've clearly marked
Do the following....
Make a normal Windows Project
Add another project to the solution - Select Windows Control Library
In the new UserControl... Draw a new button (no need to rename)
now go into the Code of the USer control and Paste the Following:
Private Delegate Sub DataSet_WorkCompleted(ByVal ObjRows() As DataRow)
Private m_ResultCallback As DataSet_WorkCompleted
Private ObjSearchResults As SearchResults
Private WithEvents ObjFrmResults As New Form1
Private Sub Cmd_Search_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'The Search button was Clicked.. Open the Wrapper and Populate it with the Parameters and SP info
m_ResultCallback = AddressOf Populate_Results
ObjSearchResults = New SearchResults(m_ResultCallback)
Dim ObjThread As New Threading.Thread(AddressOf ObjSearchResults.Search)
Catch ex As Exception
Private Sub Populate_Results(ByVal ObjDataRows() As Data.DataRow)
'Show the form
ObjFrmResults.TopMost = True
Private Class SearchResults
Private m_CallBackThread As DataSet_WorkCompleted
Public Sub New(ByRef CallBackWhenCompleted As DataSet_WorkCompleted)
m_CallBackThread = CallBackWhenCompleted
Public Sub Search()
Dim ObjRow(5) As DataRow
'This is where the DB call goes...
'By now the ObjRow would be populated also...
End Sub 'BREAKPOINT HERE <-------
Now... Rebuild the solution and paste the Usercontrol onto the first project's form....
After breakpointing the 'End Sub' that i've marked.... Run the project and click the Button, You should see a new form (topmost for debug) appear on top of the existing form and the breakpoint kick off...
This is where my results are displayed.... but as soon as you Step through so the cursor goes past the End Sub, the Form disappears
I think this is something to do with the GC killing it all off because the form is obviously running on the same thread (my best guess) but i can't figure out how to make the form stay :/
If you can figure out this little puzzle the 500 is yours :D
Thanks in Advance