2014-11-02 139 views
1

我試圖運行此代碼,但只運行第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 

回答

2

您無法從後臺線程訪問/更新UI元素。只有主UI線程才能對UI對象執行操作。這適用於WinForms和WPF。

對於WinForms,您可以使用BeginInvoke方法並傳入將在UI線程中調用的委託。對於WPF,您可以使用Dispatcher對象。