原理先不说了,先举个示例,有兴趣的话大家可以一起讨论
1.新建一个工程,类型选择ActiveX Exe,工程重命名为TestExe 在工程中添加一个Form,放上一个Timer控件. 将Class1改名为clsTest,注意其Instancing要设置为5-MultiUse, 以下是其代码:
Option Explicit Private Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long) Private WithEvents oTimer As Timer Private frmTmp As Form1 Private lTotalLoop As Long Private bDoStop As Boolean Private lInterval As Long
Public Event Progress(ByVal lProgress As Long)
Public Sub StartSub(ByVal lTotal As Long) lTotalLoop = lTotal oTimer.Enabled = True End Sub
Public Sub StopSub() bDoStop = True End Sub
Private Sub Class_Initialize() Set frmTmp = New Form1 Load frmTmp Set oTimer = frmTmp.Timer1 oTimer.Enabled = False bDoStop = False lInterval = 1 End Sub
Private Sub DoLoop() Dim i As Long For i = 0 To lTotalLoop Sleep (lInterval) RaiseEvent Progress(i) If bDoStop = True Then Exit Sub End If Next End Sub
Private Sub Class_Terminate() Unload frmTmp Set frmTmp = Nothing Set oTimer = Nothing End Sub
Private Sub oTimer_Timer() oTimer.Enabled = False DoLoop End Sub
Public Property Get lMillisecs() As Long lMillisecs = lInterval End Property
Public Property Let lMillisecs(ByVal vNewValue As Long) lInterval = vNewValue End Property
在TestExe Property(工程属性)的Threading Model中,设置Thread per Object,或者选择Thread pool中设置大于1的数值.如把Thread pool设置为2, 则调用此ActiveX Exe最多能同时有两个线程, 更多的请求将放置于队列中. 编译TestExe
下面来测试我们的多线程程序:
新建一个Standard Exe工程,在Reference中选择刚刚做好的TestExe.exe 在Form1中添加两个ListBox,两个CommandButton,Command1为开始,Command2为停止 以下是Project1.Form1的代码:
Option Explicit Private WithEvents oTest1 As TestEXE.clsTest Private WithEvents oTest2 As TestEXE.clsTest
Private Sub Command1_Click() Set oTest1 = New TestEXE.clsTest oTest1.lMillisecs = 100 oTest1.StartSub (1000) Set oTest2 = New TestEXE.clsTest oTest2.lMillisecs = 100 oTest2.StartSub (1000) End Sub
Private Sub Command2_Click() oTest1.StopSub oTest2.StopSub End Sub
Private Sub Form_Unload(Cancel As Integer) Set oTest1 = Nothing Set oTest2 = Nothing End Sub
Private Sub oTest1_Progress(ByVal lProgress As Long) List1.AddItem lProgress List1.ListIndex = List1.ListCount - 1 End Sub
Private Sub oTest2_Progress(ByVal lProgress As Long) List2.AddItem lProgress List2.ListIndex = List2.ListCount - 1 End Sub
启动Project1,点击Command1,怎么样,看见来效果了吗? 试着把TestExe的Thread pool改成1看看会怎么样? 这是我认为最简单且稳固的多线程实现方法了,大家有什么好的想法欢迎留言.
|