Hi
Based on my test, the new spawned thread will not terminate if we did not
terminate it or it terminate itself even if the main thread is exit.
When it a winform application started, it will have a default thread, i.e.
the Main Thread(Winform UI thread), if we start a new thread, then the
process will have two threads.
Even if we terminate the main thread(by closing the winform window), the
other thread will keep running, and the process will not exit until all the
threads exits.
[Test codoe, the threadproc will keep running,even if we close the winform
window]
Private Sub threadproc()
Try
While True
System.Diagnostics.Debug.WriteLine(Now().ToString( ) &
System.Threading.Thread.CurrentThread.Name)
System.Threading.Thread.Sleep(3000)
End While
Catch ex As Exception
System.Diagnostics.Debug.WriteLine("Thread " & ex.ToString())
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Try
Dim th As New Threading.Thread(AddressOf threadproc)
th.Name = "Test Thread"
th.Start()
Catch ex As Exception
End Try
End Sub
For your scenario, you may try to control the thread state in the winform
application.
NOTE: the code below is for test purpose, you may need to change according
to your scenario.
'Give a bool value to indicate if we need to thread to exit
Dim bContinue As Boolean = False
Private Sub threadproc()
Try
While bContinue
System.Diagnostics.Debug.WriteLine(Now().ToString( ) &
System.Threading.Thread.CurrentThread.Name)
System.Threading.Thread.Sleep(1000)
End While
Catch ex As Exception
System.Diagnostics.Debug.WriteLine("Thread " & ex.ToString())
End Try
End Sub
Dim th As New Threading.Thread(AddressOf threadproc)
'Start thread
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
th.Name = "Test Thread"
bContinue = True
th.Start()
End Sub
'suspend thread if needed
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
If th.ThreadState And (Threading.ThreadState.Running Or
Threading.ThreadState.WaitSleepJoin) Then
th.Suspend()
End If
End Sub
'resume the thread from suspended state
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click
If th.ThreadState And Threading.ThreadState.Suspended Then
th.Resume()
End If
End Sub
'exit the thread by set the bContinue flag to false.
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button4.Click
bContinue = False
If th.ThreadState And Threading.ThreadState.Suspended Then
th.Resume()
End If
End Sub
Best regards,
Peter Huang
Microsoft Online Partner Support
Get Secure! -
www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.