如何在新线程中修改文本框值

时间:2018-09-21 09:49:34

标签: vb.net multithreading

我有这个Sub:

Public Sub obtenerValorDeFichero()
    Dim ruta As String
    ruta = "file.txt"
    Dim myFile As New FileInfo(ruta)
    Dim sizeInBytes As Long = myFile.Length
    While (Convert.ToInt32(sizeInBytes.ToString) < 4)
        myFile.Refresh()
        sizeInBytes = myFile.Length
    End While
    Threading.Thread.Sleep(500)
    Me.TextBox3.Text = File.ReadAllText(ruta).Trim
End Sub

我通过这种方式在新代码中调用它:

Dim myThread As System.Threading.Thread
myThread = New System.Threading.Thread(Sub() obtenerValorDeFichero())
myThread.Start()

但是当尝试更改Me.Textbox3.Text值时会崩溃,我该怎么办?

1 个答案:

答案 0 :(得分:1)

我使用这种方法从创建线程之外的线程更新TextBox。

func test()

然后在MyClass中可以替换

Private Delegate Sub SetTextBoxDelegate(ByVal TB As TextBox, ByVal txt As String)

Private Sub SetTextBoxWithInvoke(ByVal TB As TextBox, ByVal txt As String)
    If TB.InvokeRequired Then
        TB.Invoke(New SetTextBoxDelegate(AddressOf SetTextBoxWithInvoke), New Object() {TB, txt})
    Else
        TB.Text = txt
    End If
End Sub

使用

obtenerValorDeFichero()

致谢。