事实上使用visual basic的activex exe技术可以轻松的实现多线程处理.
原理先不说了,先举个示例,有兴趣的话大家可以一起讨论
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看看会怎么样? 这是我认为最简单且稳固的多线程实现方法了,大家有什么好的想法欢迎留言.
新闻热点
疑难解答