ListBox多线程

时间:2018-09-15 23:06:47

标签: vb.net listbox

我要解决的问题。
我有一个应用程序,该应用程序读取其中包含.mp3文件的文件夹。
我想使用多线程同时使用文件名和持续时间来填充ListView,因为如果我在单线程中执行它会花费很长时间。

我似乎无法像我尝试的那么快
任何帮助将不胜感激。

Public arr(2) As String
Public itm As ListViewItem
Dim T1, t2 As Thread

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    T1 = New Threading.Thread(AddressOf Me.t1worker)
    T1.Start()
    t2 = New Threading.Thread(AddressOf t2worker)
    t2.Start()
 End Sub     

Public Sub t1worker()
    For Each file As String In IO.Directory.GetFiles("f:\mvideo", "*.*")
        arr(0) = IO.Path.GetFileName(file)         
    Next
End Sub

Public Sub t2worker()
    Dim Duration As String
    Dim w As New WMPLib.WindowsMediaPlayer       
    For Each file As String In IO.Directory.GetFiles("f:\mvideo", "*.*")
        If AllowedExtension.Contains(IO.Path.GetExtension(file).ToLower)  
            Dim m As WMPLib.IWMPMedia = w.newMedia(file)
            Duration = m.durationString
            arr(1) = Duration
        End If

        arr(1) = Duration
        itm = New ListViewItem(arr)
        trackinfo.Items.Add(itm)
    Next
End Sub

2 个答案:

答案 0 :(得分:0)

忘记线程,尝试这个只是为了咧嘴笑。 我假设您的listview称为trackinfo。 符合注释和解释。

Private Sub FillListView()
    'Using a List(Of T) because the number of items is indeterminate.
    Dim lstMP3 As New List(Of ListViewItem)
    For Each file As String In IO.Directory.GetFiles("f:\mvideo", "*.*")
        Dim liMP3 As New ListViewItem
        liMP3.Text = IO.Path.GetFileName(file)
        'You probably need to send the full path to the function
        liMP3.SubItems.Add(GetDuration("Path & fileName"))
        lstMP3.Add(liMP3)
    Next
    'The .BeginUpdat /.EndUpdate prevents the listview from repainting of each
    'line addition greatly speeding up the process
    trackinfo.BeginUpdate
    trackinfo.Items.AddRange(lstMP3.ToArray)
    trackinfor.EndUpdate
End Sub
Private Function GetDuration(fileName As String) As String
    'Not at all sure how this works so you may have to adjust
    If AllowedExtension.Contains(IO.Path.GetExtension(fileName).ToLower) Then
        Dim m As WMPLib.IWMPMedia = w.newMedia(fileName)
        Duration = m.durationString
    End If
    Return Duration
End Function

答案 1 :(得分:0)

我使用数据库解决了这个问题。将文件名和持续时间加载到数据库中。然后从数据库中填充列表。