0

Can anyone please tell me how to fix this? I keep getting a "Cross-thread operation not valid error." I feel like I need to somehow add a public event within the separate thread, but don't know how. Thanks

Public Class Form2
    Public WithEvents _tasks As New Tasks

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        _tasks.StartThread()
    End Sub

    Public Sub task1(msg As String) Handles _tasks.DoTask1
        TextBox1.Text &= msg
    End Sub
End Class

Public Class Tasks
    Public Event DoTask1(msg As String)

    Public _thread As New Thread(AddressOf TasksThread)

    Public Sub StartThread()
        _thread.Start()
    End Sub

    Public Sub TasksThread()
        Do
            RaiseEvent DoTask1("1")
            Thread.sleep(1000)
        Loop While True
    End Sub
End Class
wayofthefuture
  • 8,339
  • 7
  • 36
  • 53
  • possible duplicate of [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) – Erik Noren Feb 27 '14 at 03:43

2 Answers2

1

Try this:

Public Sub task1(msg As String) Handles _tasks.DoTask1

    If TextBox1.InvokeRequired Then
        TextBox1.Invoke(Sub() TextBox1.Text &= msg)
    Else
        TextBox1.Text &= msg
    End If

End Sub
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417
  • Just to confirm, when trying to access a control on a form from another thread, I must use Invoke or BeginInvoke. If I am trying to access a class from another thread, I can either pass the class by reference or use RaiseEvent, I just have to make sure that I synclock variables that are being written to within that class. Does this sounds like a good standard? Do you know a good book I can read about multithreading? Everything is so hard to understand. Thanks – wayofthefuture Feb 27 '14 at 16:52
0

You're modifying a UI control from a thread other than the UI thread. You need to marshal your event handler call to Textbox1.Text.

There are dozens of similar SO questions and answers related to this. Here's one.

Community
  • 1
  • 1
Erik Noren
  • 4,279
  • 1
  • 23
  • 29
  • So I guess RaiseEvent is not meant for cross threads, I have to use Invoke? – wayofthefuture Feb 27 '14 at 03:47
  • RaiseEvent will trigger an event that typically will fire on its own thread. Your handler `Public Sub task1(msg As String) Handles _tasks.DoTask1` will therefor be executing from a non-UI thread. Since it tries to touch a UI object, that's where you'll get the exception and that's where you'll need to use Invoke or some other method to marshal the call back to the UI thread. – Erik Noren Feb 27 '14 at 03:51