【问题标题】:Set Label From Thread从线程设置标签
【发布时间】:2015-06-23 05:21:36
【问题描述】:

Form1.vb

Imports System.Threading

Public Class Form1

Dim demoThread As Thread

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim Start As New Class1
    Me.demoThread = New Thread( _
            New ThreadStart(AddressOf Start.ThreadProcSafe))

    Me.demoThread.Start()

End Sub
Delegate Sub SetTextCallback([text] As String)
Public Sub SetText(ByVal [text] As String)

    ' InvokeRequired required compares the thread ID of the 
    ' calling thread to the thread ID of the creating thread. 
    ' If these threads are different, it returns true. 
    If Me.textBox1.InvokeRequired Then
        Dim d As New SetTextCallback(AddressOf SetText)
        Me.Invoke(d, New Object() {[text]})
    Else
        Me.textBox1.Text = [text]
    End If
End Sub
End Class

Class1.vb

Public Class Class1

Public Sub ThreadProcSafe()
    Form1.SetText("This text was set safely.")
End Sub
End Class

谁能告诉我为什么这不更新文本框?

当 ThreadProcSafe 在 Form1 内部被调用(并且仍然由线程启动)但当它从类外移到另一个类时,它可以工作,没有警告或错误但不会更新。

【问题讨论】:

    标签: vb.net multithreading winforms


    【解决方案1】:

    原因是您在第二个代码 sn-p 中引用了默认实例。默认实例是线程特定的,因此第二个代码 sn-p 将创建一个 Form1 类型的新实例,而不是使用现有实例。您的 Class1 需要引用 Form1 的原始实例。

    如果这不切实际,那么解决方案是不在表单中进行委托,而是在访问表单的类中使用SynchronizationContext 类进行。

    【讨论】:

    • 我想我明白了!需要测试这是否是线程安全的,但是当我使用表单引用调用线程并且类使用它来调用 setText 函数时它确实有效。
    猜你喜欢
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    相关资源
    最近更新 更多