问题,利用多线程解决界面卡死时,控件不能在新建的线程中访问。
解决方法,
可使用Invoke或BeginInvoke,在拥有此控件的基础窗口句柄的线程上执行指定的委托。
Invoke 方法 (Delegate) :在拥有此控件的基础窗口句柄的线程上执行指定的委托;
BeginInvoke 方法 (Delegate) :在创建控件的基础句柄所在线程上异步执行指定委托。
代码:
-
Public Class Form1
-
Private Delegate Sub AddLstItemDelegate(ByRef lst As ListBox, ByVal txt As String)
-
Private Sub AddLstItemInvoke(ByRef lst As ListBox, ByVal txt As String)
-
lst.Items.Add(txt)
-
End Sub
-
Private th As Threading.Thread
-
-
Private Sub TaskTest()
-
-
Dim i As Integer
-
For i = 0 To 20
-
Threading.Thread.Sleep(1000)
-
ListBox1.Invoke(New AddLstItemDelegate(AddressOf AddLstItemInvoke), New Object() {ListBox1, i.ToString})
-
Next
-
-
End Sub
-
-
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
-
-
th = New Threading.Thread(AddressOf TaskTest)
-
th.Start()
-
End Sub
-
End Class
版权声明:本文为博主原创文章,未经博主允许不得转载。