从一个线程在我的listview中插入行

时间:2014-09-16 06:14:03

标签: vb.net multithreading listview delegates

我必须在vb中创建一个非常简单的应用程序。我的应用程序包含一个按钮和一个列表视图。在我的应用程序中,我必须运行线程,并在列表视图中插入执行的线程的名称和时间。当我点击线程按钮

时,我的代码就开始了

我的代码如下

Private Sub btnThreading_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThreading.Click
    Try       
        For index = 0 To 3    
            Dim th As New Threading(index)                
            Me.Invoke(New DoStuffDelegate(AddressOf th.Run))
        Next    
        lstText.View = View.Details
        lstText.Columns.Add("Thread Name")
        lstText.Columns.Add("Time")
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

页面线程如下

    Public Class Threading
    Private threadName As String
    Dim value As Date    
    Private Delegate Sub DoStuffDelegate()
    Dim lockthis As New Object       
    Sub New(ByVal ThreadName As String)
        Me.threadName = "Thread Number : " & ThreadName
    End Sub        

    Public Sub Run()    
            For index = 0 To 3
                Thread.Sleep(1000)
                value = Date.Now
                Console.WriteLine(threadName & " Time : " & value)
                Dim item3 As New ListViewItem(Me.threadName)
                item3.SubItems.Add(Me.value)
                Form1.lstText.Items.AddRange(New ListViewItem() {item3})
            Next   
    End Sub      
End Class

如果我使用没有代理的线程,如下所示

Dim th As New Threading(index) Dim trd = New Thread(AddressOf th.Run) trd.start()

,我的输出窗口显示名称和线程,例如

主题号码:1时间:9/15/2014 9:51:00
主题:0时间:2014/9/15 9:51:00
主题:2时间:2014/9/15 9:51:00
主题:3时间:9/15/2014 9:51:00

但在列表视图中没有显示任何内容。但如果我选择像下面那样使用委托,

    Dim th As New Threading(index)
    Me.Invoke(New DoStuffDelegate(AddressOf th.Run))

它在输出中显示以下内容

主题编号:1时间:2014年9月15日9:50:59
主题:0时间:2014/9/15 9:51:00
主题:2时间:2014/9/15 9:51:01
主题:3时间:9/15/2014 9:51:02

它在listview中显示它。它可以工作,但不像线程那样执行代码。但最后当我使用以下代码时

Dim th As New Threading(index)
Dim trd = New Thread(AddressOf th.Run)
Me.Invoke(New DoStuffDelegate(AddressOf trd.Start))

,我的输出窗口显示名称和线程,例如

主题号码:1时间:9/15/2014 9:51:00
主题:0时间:2014/9/15 9:51:00
主题:2时间:2014/9/15 9:51:00
主题:3时间:9/15/2014 9:51:00

但在列表视图中没有显示任何内容。

我希望列表视图显示此

主题号码:1时间:9/15/2014 9:51:00
主题:0时间:2014/9/15 9:51:00
主题:2时间:2014/9/15 9:51:00
主题:3时间:9/15/2014 9:51:00

所有线程应该有相同的时间,所有线程应该同时开始,它们应该出现在我的列表视图中。

请帮助,我已经工作了两个星期,我找不到任何解决方案!

1 个答案:

答案 0 :(得分:0)

您在ListView添加了什么?名字和时间,对吧?因此,当您在UI线程上调用方法时,请传递名称和时间。不要等到你在UI线程上花时间,因为很明显这会更晚。