如何将文本设置为在另一个线程中创建的元素



在开始之前,我知道已经有很多答案了,但让我解释一下。

我基本上希望将某些文本附加到RichTextbox元素上,它对我来说像一个记录器一样,将文件从文件处理中告知用户,但是文本通过for for loop将其附加到RichTextbox,如果我执行此操作在同一类" form1.vb"中循环UI冻结直到循环完成。

我决定在单独的线程中运行循环以避免使用UI冻结,并且在这里我的问题开始。

form1.vb

Imports System.Threading

Public Class Form1
    Dim myThread As Thread
    Private Sub appendMyText()
        ' Cross-thread operation not valid: Control txtLogger accessed from a thread other than the thread it was created on.
        txtLogger.AppendText("Hello World" & vbNewLine)
    End Sub
    Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
        myThread = New Thread(New ThreadStart(AddressOf appendMyText))
        myThread.Start()
    End Sub
End Class

我无法从另一个线程访问txtlogger元素,所以我尝试了MSDN示例https://msdn.microsoft.com/en-us/library/ms171728(v = vs.110).aspx?cs-save-lang = 1& cs-& cs-lang = vb#code-snippet-2

它向我展示了如何使用委托访问元素进行线程安全调用。

所以我的编辑代码是

form1.vb

Imports System.Threading
Public Class Form1
    Dim myThread As Thread
    Delegate Sub AppendMyText(ByVal text As String)
    ' Add the text to RichTextBox
    Private Sub addText(ByVal txt As String)
        If txtLogger.InvokeRequired Then
            Dim myDelegate = New AppendMyText(AddressOf addText)
            Me.Invoke(myDelegate, {txt})
        Else
            txtLogger.AppendText(txt)
        End If
    End Sub
    ' Call the method that add text to RichTextBox
    Private Sub threadSafe()
        Me.addText("Hello World" & vbNewLine)
    End Sub
    Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
        myThread = New Thread(New ThreadStart(AddressOf threadSafe))
        myThread.Start()
    End Sub
End Class

代码确实有效,文本附加到RichTextbox,但是所有代码都在同一类Form1.vb

在我的原始项目中,for循环是在另一个类中执行的,我将在这里命名为" class1.vb"。

这是代码示例

class1.vb

Public Class Class1
    Public Sub count()
        Dim i As Integer
        For i = 0 To 100
            ' this method will be executed by thread "myThread"
            ' how to append text to txtLogger from here?
            Debug.WriteLine("Index: {0}", i)
        Next
    End Sub
End Class

将表格引用到类

在您的表格中

Dim MyClass as Class1
MyClass = New Class1(Me)

在您的班级中

Public Class Class1
     Private Parent_From as Form1
     Public Sub New(Parent as Form1)
           Parent_From = Form
     End sub
     Public Sub count()
        Dim i As Integer
        For i = 0 To 100
            ' this method will be executed by thread "myThread"
            Parent_Form.addTExt("Whatever")
            Debug.WriteLine("Index: {0}", i)
        Next
    End Sub
End CLass

相关内容

  • 没有找到相关文章

最新更新