基于事件通知的线程等待(vb.net)

前端之家收集整理的这篇文章主要介绍了基于事件通知的线程等待(vb.net)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这个帖子中提及了线程等待的问题,原方法是用循环判断线程状态来决定是否继续执行的思路。这种方法的主要问题是浪费资源,虽然用Sleep可以减少cpu的占用量,但远不如用事件通知方法来的优雅。

下面贴出基于事件通知的线程等待的代码,完全可以举一反三。

(魏滔序原创,转帖请注明出处。)

@H_404_7@Imports System Imports System.Threading Public Class ThreadClass Private Shared Event Completed As EventHandler Private Shared ThreadCount1 As Integer = 11 '创建11个线程 Private Shared ThreadCount2 As Integer = 0 Public Shared Sub Main() Dim Thread As Thread ThreadCount2 = 0 '事件与过程绑定 AddHandler Completed,AddressOf ThreadCompleted '创建并执行线程 For i As Integer = 1 To ThreadCount1 Thread = New Thread(New ParameterizedThreadStart(AddressOf ThreadProcess)) Thread.Start(i) Next Console.ReadKey() End Sub '每个线程结束的时候都要调用的事件 Private Shared Sub ThreadCompleted(ByVal sender As Object,ByVal e As EventArgs) ThreadCount2 += 1 If ThreadCount1 = ThreadCount2 Then Console.WriteLine("这是所有线程执行完才执行的内容") End If End Sub '线程处理过程 Private Shared Sub ThreadProcess(ByVal parameter As Object) For i As Integer = 0 To 100 Console.WriteLine("这是线程{0}中执行的内容",parameter.ToString) Next '触发事件 RaiseEvent Completed(Nothing,Nothing) End Sub End Class

猜你在找的VB相关文章