i’m trying to learn multithreading and i’m stuck on this sample
Imports System.Threading
Public Class Form1
Dim myThread As System.Threading.Thread = New Thread(AddressOf Me.AddItems)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myThread.Start()
End Sub
Public Sub AddItems()
Dim i As Int32
Dim n As Int32 = 1
Dim s As String = ""
For i = 0 To 100
s = n.ToString
ListBox1.Items.Add(s)
n *= 2
Thread.CurrentThread.Sleep(100)
Next
End Sub
End Class
i get the following error:
“Cross-thread operation not valid: Control ‘ListBox1’ accessed from a
thread other than the thread it was created on”
ListBox1.Items.Add(s)is the problem.You cannot update the UI from a non-UI thread.
ListBox1was created by, and belongs to the main UI thread.You should be using Control.Invoke to perform the UI update.
Use something like: