[RESOLVED] 2nd thread does not end when flagged to end.
Good day,
When the main thread is busy, I want to display a progress bar and then close it when the main thread is finished work. The display of Form2 and it's progress bar work fine. But when the stopFlag is set, the 2nd thread does not see it and does not execute the Form2.Close() code. It only executes it after I manually close Form2. The below code is a simple app that demonstrates the problem. I am running Win 10 and VS 2019. Any ideas would be appreciated. Thanks
Code:
Imports System.Threading
Public Class Form1
Dim stopFlag As Boolean = False
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
stopFlag = False
Dim t = New Thread(AddressOf ShowProgress)
t.Start()
Dim y = 0
For x = 1 To 10000
While y < 200000
y = y + 1
End While
y = 0
Next
stopFlag = True
MessageBox.Show("Done")
End Sub
Private Sub ShowProgress()
Form2.ShowDialog()
Form2.BringToFront()
While stopFlag = False
End While
Form2.Close()
End Sub
End Class
Re: 2nd thread does not end when flagged to end.
You're doing it backwards. Display the ProgressBar on the main thread and do the work on the secondary thread. See here for a simple implementation that you can use as is.
Re: 2nd thread does not end when flagged to end.
As for your existing code, it's terrible. That While loop is what's known as a "busy wait", which means that, instead of actually waiting and doing nothing, the code is working at full throttle but not going anywhere or doing anything useful. That is something that you should NEVER do. At the very least, put a short delay inside the loop so that the code will actually wait there for a while instead of spinning incessantly.
Apart from that, the code can never even get to that loop as it is. Think about what ShowDialog actually does.