任何人都可以告诉我如何解决这个问题?我不断收到“跨线程操作无效错误”。我觉得我需要以某种方式在单独的线程中添加公共事件,但不知道如何。感谢
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
答案 0 :(得分:1)
试试这个:
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
答案 1 :(得分:0)
您正在从UI线程以外的线程修改UI控件。您需要将事件处理程序调用封送到Textbox1.Text
。
有许多类似的SO问题和答案与此相关。这是one。