如何通过不同线程访问richtextbox

How to access richtextbox via different thread

大家好,我的问题是如何在线程中访问 (update/read) richtextbox。 我刚刚创建了一个非常简单的代码,以便您了解我在做什么。网上搜了一些文章提到invoke, delegate, backgroundworker,希望有人能来告诉我具体怎么用。非常感谢

Imports System.Threading

Public Class form1

Dim flag As Boolean = True
Dim startbtn As Thread
Dim stopbtn As Thread

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    startbtn = New Thread(AddressOf startfuction)
    startbtn.Start()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    stopbtn = New Thread(AddressOf stopfunction)
    stopbtn.Start()
End Sub

'************** thread 1

Private Sub startfuction()
    flag = True
    While flag = True
        richtextbox1.text = "Your process started"         'error
    End While

End Sub

'************** thread 2
Private Sub stopfunction()
    flag = False
    startbtn.Abort()
    MsgBox("You ended the process")
End Sub

结束Class

Imports System.Threading

Public Class Form1

Dim flag As Boolean = True
Dim startbtn As Thread

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    startbtn = New Thread(AddressOf startfuction)
    startbtn.Start()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    flag = False
    MsgBox("You ended the process")
End Sub

'************** thread 1

Private Sub startfuction()
    flag = True
    While flag = True
        Me.Invoke(Sub() RichTextBox1.Text = "Your process started")         'error
    End While
    Me.Invoke(Sub() RichTextBox1.Text = "Your process stopped")         'error

End Sub
End Class

编辑 1

此外,当 运行 线程时,当您关闭您的应用程序时,您可能会 运行 遇到问题,因为您的线程会过早结束..

做类似的事情

Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    flag = False
    Application.DoEvents()
End Sub