多线程编程,引发事件
Imports System.Threading
Public Class counter
Public max As Integer = 0
Public Event DoneCounting(ByVal Number As Integer)
Sub count()
Dim total As Integer = 0
For i As Integer = 0 To 10
For loopIndex As Integer = 1 To max
total += 1
Next loopIndex
Thread.Sleep(500)
RaiseEvent DoneCounting(total) '如果这是一个线程,也可以这样引发事件
Next i
End Sub
End Class
Dim thread1 As New Thread(AddressOf counterObject.count)
AddHandler counterObject.DoneCounting, AddressOf a'然后这样处理事件,a是处理函数的地址
Dim thread1 As New Thread(AddressOf counterObject.count)'定义线程
counterObject.max = 10000'......某些赋值操作后启动线程
thread1.Start()注意:windows程序测量时间间隔精度大于毫秒,以至于sleep(1) and sleep(10)将提供相同的时间间隔。
在某些线程还在执行的时候,我关闭了窗体,可是线程中有对窗体中文本框的操作,结果引发了异常。
Private Sub a(ByVal x As Integer)
Try
TextBox1.AppendText(x.ToString & Chr(13) & Chr(10))
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
将会谈出多个对话框,直到线程退出,应用程序才会退出。这是点窗体的关闭按钮的结果。
Application.Exit()也是一样。
那么,在有线程运行的时候,如何才能简单的强行关闭应用程序呢?
如果使用join,程序将会挂起,直到线程完成或被中断。