Reputation: 141
I'm trying to run this code, but when running only the first n listbox looping , the others remain empty. I would like to run the subroutine code (an infinite loop) for each listbox in the form at the same time
This is the Main Form:
Public Class Form1
Private listSettings As New List(Of ListBox)
Private nameSettings As New List(Of Label)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Variabili Grafiche
Dim lSettings As ListBox
Dim i As Integer
i = 0
Dim n As Integer
Dim width As Integer
Dim height As Integer
'Variabili Lettura File
Dim path As New IO.DirectoryInfo("C:\BatchDomoLake\config\")
Dim diar1 As IO.FileInfo() = path.GetFiles()
Dim dra As IO.FileInfo
'Lettura File e Grafica
For Each dra In diar1
n = n + 1
Next
Dim T(n) As Thread
width = (Me.Size.Width() / n)
height = (Me.Size.Height() / 2)
For Each dra In diar1
lSettings = New ListBox
With lSettings
.Location = New Point(10 + (width * i), 40)
.Name = "lst" & dra.Name.Replace(".conf", "")
.Size = New Size(width - 35, height - 40)
.Visible = True
End With
Me.listSettings.Add(lSettings)
Me.Controls.Add(lSettings)
Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(dra.FullName)
Dim a As String
Do
a = reader.ReadLine
If a IsNot Nothing Then
lSettings.Items.Add(a)
End If
Loop Until a Is Nothing
'Thread
T(i) = New Threading.Thread(AddressOf snmpThread)
T(i).Start(lSettings)
i = i + 1
Next
End Sub
This is the subroutine i would like to use for each created listbox:
Private Delegate Sub snmpThreadDelegate(ByVal list As ListBox)
Private Sub snmpThread(ByVal list As ListBox)
If list.InvokeRequired Then
list.Invoke(New snmpThreadDelegate(AddressOf snmpThread), New Object() {list})
Else
Dim count As Integer
Dim i As Integer
count = list.Items.Count - 1
Do
For i = 0 To count Step 1
list.SetSelected(i, True)
Thread.Sleep(100)
Next
Loop
End If
End Sub
Upvotes: 1
Views: 37
Reputation: 11920
You cannot access/update your UI elements from background threads. Only main UI thread can do operations on your UI objects. This applies to both WinForms and WPF.
For WinForms, you can use BeginInvoke method and pass in a delegate that would be invoked in your UI thread. For WPF, you can use Dispatcher object.
Upvotes: 2