多线程,同时取消(转自网络)
来源:互联网 发布:淘宝网注册首页 编辑:程序博客网 时间:2024/06/04 19:23
Public CancelThread As New System.Threading.ManualResetEvent(False) Public ThreadisCanceled As New System.Threading.ManualResetEvent(False) Private Sub SomeLongTask() Dim LoopCount As Integer Dim Loops As Integer = 10 ' 在 While 循环中运行 10 秒钟代码,或者 ' 直至设置了 CancelThread。 While Not CancelThread.WaitOne(0, False) And LoopCount < Loops ' 此处执行某种类型的任务。 System.Threading.Thread.Sleep(1000) ' 休眠 1 秒钟。 LoopCount += 1 End While If CancelThread.WaitOne(0, False) Then ' 确认设置了 ManualResetEvent CancelThread。 ThreadisCanceled.Set() MsgBox("取消线程") Else MsgBox("线程运行结束") End If End Sub Public Sub StartTask() ' 启动新线程。 Dim th As New System.Threading.Thread(AddressOf SomeLongTask) CancelThread.Reset() ThreadisCanceled.Reset() th.Start() MsgBox("线程已启动") End Sub Public Sub CancelTask() ' 停止任何由 StartTask 过程启动的线程。 ' 注意,此线程同时接收和发送 ' 同步事件以协调线程操作。 CancelThread.Set() ' 设置 CancelThread 以通知线程停止。 If ThreadisCanceled.WaitOne(4000, False) Then ' 最多等待 4 秒钟,以便线程 ' 确认它已经停止。 MsgBox("线程已停止。") Else MsgBox("线程无法停止。") End If End Sub