JumpyNET Posted March 9, 2009 Posted March 9, 2009 I want to catch events in my main form and change the title to match the input from the event. I'm getting errors about crossthreading. Can some one please help me get this small test program working? Here is the whole code: Public Class Form1 Private WithEvents Worker As New WorkerClass Private Sub Worker_ProgressChanged(ByVal Progress As Integer) Handles Worker.ProgressChanged Me.Text = Progress End Sub End Class Public Class WorkerClass Public Event ProgressChanged(ByVal Progress As Integer) Private t As Threading.Thread Public Sub New() t = New Threading.Thread(AddressOf MainThread) t.Name = "BackgroundThread" t.IsBackground = True t.Start() End Sub Private Sub MainThread() Dim Progress As Integer = 0 Do Until Progress = 10 Threading.Thread.Sleep(1000) Progress += 1 RaiseEvent ProgressChanged(Progress) Loop End Sub End Class Quote
Diesel Posted March 9, 2009 Posted March 9, 2009 You have to change the form text from the same thread that the form was created, which you can access in a function by using the Invoke method. To verify whether you are in form's originating thread, you can use the Control.InvokeRequired property. I would move the operations out of the event method first. Private Sub Worker_ProgressChanged(ByVal Progress As Integer) Handles Worker.ProgressChanged ChangeTitle(Progress) End Sub Delegate Sub ChangeTitleDelegate(ByVal Title As String) Private Sub ChangeTitle(ByVal Title As String) If (InvokeRequired) Then Invoke(New ChangeTitleDelegate(AddressOf ChangeTitle), Title) Else Me.Text = Title End If End Sub Quote
JumpyNET Posted March 9, 2009 Author Posted March 9, 2009 Thank you very much! I never really understood threading. Can you guys recommend a good book on the subject (something that starts from scratch)? Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.