我正在尝试运行此代码,但是当仅运行前n个列表框循环时,其他代码仍为空。我想同时为表单中的每个列表框运行子例程代码(无限循环)
这是主要表格:
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
这是我想为每个创建的列表框使用的子程序:
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
答案 0 :(得分:2)
您无法从后台线程访问/更新UI元素。只有主UI线程才能对UI对象执行操作。这适用于WinForms和WPF。
对于WinForms,您可以使用BeginInvoke方法并传入将在UI线程中调用的委托。对于WPF,您可以使用Dispatcher对象。