-3

I've got this 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

And I'm calling it in the New code by this way:

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

But it crashes when try's to change the Me.Textbox3.Text value, how can i do it?

marcss
  • 253
  • 2
  • 14
  • What is the error you get when it crashes? – Lajos Arpad Sep 21 '18 at 10:00
  • First: add a `try/catch` statement and print in a message box the error: `MsgBox(ex.Message)` – Simo Sep 21 '18 at 10:01
  • Invalid operation exception, Control 'textBox3' accessed from a thread other than the thread it was created on – marcss Sep 21 '18 at 10:05
  • @marcss yup, a thread cannot update the GUI on the main thread – Simo Sep 21 '18 at 10:06
  • You don't modify controls on threads other than the one they were created on. – jmcilhinney Sep 21 '18 at 10:06
  • and how can i do it? i need to modify in the form – marcss Sep 21 '18 at 10:08
  • Try to use the [BackgroundWorker](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker?redirectedfrom=MSDN&view=netframework-4.7.2) instead – Simo Sep 21 '18 at 10:09
  • For the record, a `Long` is a number just like an `Integer` (only it has a higher maximum value); you don't need to convert it. You can replace this: `While (Convert.ToInt32(sizeInBytes.ToString) < 4)` with this: `While sizeInBytes < 4`. – Visual Vincent Sep 21 '18 at 11:29

1 Answers1

1

I use this approach to update TextBox from a thread other than the thread it was created.

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

Then in obtenerValorDeFichero() you can replace

Me.TextBox3.Text = File.ReadAllText(ruta).Trim

With

SetTextBoxWithInvoke(Me.TextBox3, File.ReadAllText(ruta).Trim)

Regards.

Boris Serafimov
  • 607
  • 9
  • 20