Simple threading problem... [Resolved]
This is the first day I have tried to use threads. The code below doesnt work for me. It is supposed to call TestSub every 500 ms. I created a blank windows application in VB.NET 2005 Express Edition Beta #2 and paste this directly into the code and run -
VB Code:
Imports System.Threading
Public Class Form1
Dim THRD As Thread
Private Shared Sub TestSub()
MsgBox("Bleh", MsgBoxStyle.Information, "")
Thread.Sleep(500)
End Sub
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
THRD = New Thread(AddressOf TestSub)
THRD.Start()
THRD.IsBackground = True
End Sub
End Class
When I click the form, it is supposed to initialize and start the thread. So I click the form... and get the messagebox, and wait a few seconds, nothing has happened. I pause the app and find out, via the intermediate window, THRD.IsAlive = False
Can anyone please tell me what is wrong with this code? I'm sure its probably some simple thing I've overlooked. :)
Edit: Sorry, didnt mention, I need this thread to stay alive, I'm using a loop to keep it running (with a sleep statement), but what is the proper way?
Re: Simple threading problem...
Well you aren't using a loop in the code you've provided. After the call to Sleep the TestSub method completes and the thread exits. Unless you raise multiple MouseDown events you're only going to get one MessageBox. You should put a Do loop inside the TestSub method if you want to continually get MessageBoxes. You should also provide a While or Until condition on that loop so that you have a way to make it exit. Also, why have you made the TestSub method Shared?
VB Code:
Private exitThread As Boolean
Private Sub TestSub
Do
MessageBox.Show("Test message")
Thread.Sleep(500)
Loop Until Me.exitThread
End Sub
Private Sub Form1_MouseDown(...) Handles MyBase.MouseDown
Dim thrd As New Thread(AddressOf TestSub)
Me.exitThread = False
thrd.IsBackground = True
thrd.Start()
End Sub
You should provide a way to set exitThread to True to terminate the thread.
Re: Simple threading problem...
Right, thanks
The code I use from the thread is
VB Code:
Private Sub CallbackRecvCheck()
Do While sckTick.IsAlive
Thread.Sleep(16)
If sckObj.Connected <> bLastConnected Then
If sckObj.Connected Then
RaiseEvent Connected()
Else
RaiseEvent Disconnected()
End If
bLastConnected = sckObj.Connected
End If
If sckObj.Connected Then
If sckObj.GetStream.DataAvailable Then
RaiseEvent RecievedDataPending()
End If
End If
Loop
End Sub
Loop ends automatically when thread.abort is called