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

时间:2017-02-21 18:10:35

标签: .net vb.net cross-thread

在开始之前,我知道已经有一堆问题的答案,但让我解释一下发生了什么。

我基本上想要将一些文本附加到RichTextBox元素,它像记录器一样向我提供通知用户从文件处理中的每个动作,但是文本通过for循环附加到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-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

1 个答案:

答案 0 :(得分:2)

将表单引用传递给类

以您的形式

strcat

在你班上

Dim MyClass as Class1
MyClass = New Class1(Me)