多线程一般是不推荐用的,因为线程之间如果有共享资源的话会引起竞争,需要加锁处理;而且线程间没有时序关系,所以你在调试中可能会出现异步处理结束顺序与开始处理顺序不一致的情况(我在调试中已经发现该问题)。
创新互联主营宝山网站建设的网络公司,主营网站建设方案,成都app软件开发公司,宝山h5小程序设计搭建,宝山网站营销推广欢迎宝山等地区企业咨询
针对你提出的这个问题,采用了多线程处理,利用的是BackgroundWorker也就是异步处理控件进行了处理。
代码已经经过调试通过。欢迎交流,如有问题,留下QQ或其他联系方式。
代码如下,并附程序截图。
‘---------------------------------------------------
Imports System.ComponentModel '导入异步控件命名空间
Public Class Form1
Private howmany As Integer = 10
Private AnalysisNumber(0 To howmany - 1) As BackgroundWorker
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
creatNewBackgroundWorker()
addHandle()
startWork()
End Sub
Private Sub creatNewBackgroundWorker()
For i As Integer = 0 To AnalysisNumber.Length - 1
AnalysisNumber(i) = New BackgroundWorker
Next
End Sub
Private Sub addHandle()
For i As Integer = 0 To AnalysisNumber.Length - 1
AddHandler AnalysisNumber(i).DoWork, AddressOf AnalysisNumber_DoWork
AddHandler AnalysisNumber(i).RunWorkerCompleted, AddressOf AnalysisNumber_RunWorkerCompleted
Next
End Sub
Private Sub startWork()
For i As Integer = 0 To 9
Dim temp(0 To 9) As Integer
For j As Integer = 1 To 10
temp(j - 1) = 10 * i + j
Next
AnalysisNumber(i).RunWorkerAsync(temp)
Next
End Sub
Private Sub AnalysisNumber_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
Dim data As Integer()
data = CType(e.Argument, Integer())
Dim temp As Integer
For i As Integer = 0 To data.Length - 1
temp = data(i)
data(i) = temp * temp
Next
e.Result = data
End Sub
Private Sub AnalysisNumber_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
Dim data As Integer()
data = CType(e.Result, Integer())
For i As Integer = 0 To data.Length - 1
ListBox1.Items.Add(data(i))
Next
End Sub
End Class
多线程是用于处理复杂项目的
打个比方
你的主程序线程A中有个循环,由于代码是一行行走的,所以循环结束前下面的代码无法运行,而此时主界面的反应就类似卡死的样子,你点击按钮也没有反应,因为主线程在忙着循环呢,所以对按钮的事件代码要等待了,如果要避免这种情况,就要用到多线程,另开一个新线程专门用来执行循环代码,主界面就不会卡死了,只要在循环结束后将结果传回主线程调用就可以了,再复杂点要涉及到委托,控制了
按你的要求其实你的代码用不到多线程,只要把sleep放到两段代码中间就可以了。
新线程结束用thread.abort()
将循环放入到另一个线程中
ThreadStart ts = new ThreadStart(delegate() {
//do something
});
Thread t = new Thread(ts);
t.Start();
//going do something
在多线程中你需要定义委托来修改控件属性
比如你修改Textbox属性,则:
Delegate Sub dl_ShowTextbox(ByVal iStr As String)
Public Sub ShowTextbox(ByVal iStr As String)
If Textbox.IsDisposed Then
Return
End If
If Textbox.InvokeRequired = True Then
Dim pInvoke As New dl_ShowTextbox(AddressOf ShowTextbox)
Me.Invoke(pInvoke, New Object() {iStr})
Else
Textbox.Text = iStr
End If
End Sub
在多线程中调用
ShowTextbox( "要显示的内容" )