首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > VB Dotnet >

這點代碼錯在哪呀?怎麼編譯不了呀?该如何处理

2012-01-13 
這點代碼錯在哪呀?怎麼編譯不了呀???ImportsSystem.ThreadingPublicClassForm1PrivateSubtest()DimiAsInte

這點代碼錯在哪呀?怎麼編譯不了呀???
Imports   System.Threading

Public   Class   Form1

        Private   Sub   test()
                Dim   i   As   Integer
                For   i   =   1   To   10000
                        Me.ListBox1.Items.Add( "線程一: "   &   i)
                Next   i
        End   Sub

        Private   Sub   Button1_Click(ByVal   sender   As   System.Object,   ByVal   e   As   System.EventArgs)   Handles   Button1.Click
                Dim   th1   As   Thread
                th1   =   New   Thread(AddressOf   Me.test)
                th1.Start()
        End   Sub

End   Class

[解决办法]
跨线程调用必须用委托

Imports System.Threading

Public Class Form1

Private Delegate Sub InvokeDelegate()

Private Sub test()
ListBox1.BeginInvoke(New InvokeDelegate(AddressOf InvokeMethod))
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim th1 As Thread
th1 = New Thread(AddressOf Me.test)
th1.Start()
End Sub


Private Sub InvokeMethod()
Dim i As Integer
For i = 1 To 10000
Me.ListBox1.Items.Add( "線程一: " & i)
Next i
End Sub
End Class
[解决办法]
Imports System.Threading

Public Class Form1
Delegate Sub AddItemCallback(ByVal [text] As String)
Private Sub AddItem(ByVal [text] As String)

If Me.ListBox1.InvokeRequired Then
Dim d As New AddItemCallback(AddressOf AddItem)
Me.Invoke(d, New Object() {[text]})
Else
Me.ListBox1.Items.Add([text])
End If
End Sub

Private Sub AddItem_cls(ByVal Item As String)
AddItem(Item)
End Sub

Private Class Test
Public Index As Integer
Public Event AddItem(ByVal Item As String)
Public Sub Test()
Dim i As Integer
For i = 1 To 1000
RaiseEvent AddItem( "線程 " & Index & "; " & i)
Next i
End Sub
End Class

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim th1(3) As Thread
Dim clsTest As Test
Dim n As Integer

For n = 0 To 3
clsTest = New Test
AddHandler clsTest.AddItem, AddressOf AddItem_cls
clsTest.Index = n
th1(n) = New Thread(AddressOf clsTest.Test)
th1(n).Start()
Next

End Sub

End Class

上面这个例子,刚刚改造的,你可以参考一下,利用了很多在线程方面的基础知识。

热点排行