none
VB2005的Winform程序中,如何使用多线程(不使用Backgroundworker,采用委托的方法)? RRS feed

  • 问题

  • VB2005的Winform程序中,如何使用多线程(不使用Backgroundworker控件,要采用委托的方法)?

    在代码中不涉及窗体上的控件就没问题,但是像下面这样,用到了listbox就出错了。

    微软推荐使用委托,到底代码该怎么写,搜索了2天的帖子,头晕得厉害了。就请老师给改一下,尽量用简洁的代码事例吧。

     

    我的如下代码:

    Public Class Form1

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim t1 As New Threading.Thread(AddressOf 填充listbox1)
            Dim t2 As New Threading.Thread(AddressOf 填充listbox2)
            t1.Start()
            t2.Start()
        End Sub

        Private Sub 填充listbox1()
            For i As Integer = 0 To 9999
                Me.ListBox1.Items.Add(i.ToString)
            Next
        End Sub

        Private Sub 填充listbox2()
            For i As Integer = 0 To 9999
                Me.ListBox2.Items.Add(i.ToString)
            Next
        End Sub
    End Class

     

    运行提示:线程间操作无效: 从不是创建控件“ListBox2”的线程访问它。

     

    应该如何修改?请给VB的代码参考,不要用C#,看不懂的。多谢各位大侠!

    2008年5月8日 14:57

答案

全部回复

  •  

    Public Class Form1
        Inherits System.Windows.Forms.Form'继承于窗体类

     

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim t1 As New Threading.Thread(AddressOf 填充listbox1)
            Dim t2 As New Threading.Thread(AddressOf 填充listbox2)
            t1.Start()
            t2.Start()
        End Sub

        Private Sub 填充listbox1()
            For i As Integer = 0 To 9999
                Me.ListBox1.Items.Add(i.ToString)
            Next
        End Sub

        Private Sub 填充listbox2()
            For i As Integer = 0 To 9999
                Me.ListBox2.Items.Add(i.ToString)
            Next
        End Sub
    End Class

    2008年5月11日 8:15
  •  

    Code Snippet

    Delegate Sub LoadListBox()

    Public Class Form1

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
           dim t1 as new LoadlistBox(Addressof 填充listbox1)

           dim t2 as new LoadlistBox(Addressof 填充listbox2)

           t1.Invoke()
           t2.Invoke()
        End Sub

        Private Sub 填充listbox1()
            For i As Integer = 0 To 9999
                Me.ListBox1.Items.Add(i.ToString)
            Next
        End Sub

        Private Sub 填充listbox2()
            For i As Integer = 0 To 9999
                Me.ListBox2.Items.Add(i.ToString)
            Next
        End Sub
    End Class

     

     

    2008年5月23日 9:32