vb.net中如何結束一個線程
成都創新互聯主營新蔡網站建設的網絡公司,主營網站建設方案,重慶APP開發,新蔡h5微信小程序開發搭建,新蔡網站營銷推廣歡迎新蔡等地區企業咨詢
一般而言,如果您想終止一個線程,您可以使用System.Threading.Thread類的Abort方法. 例如:
Dim worker As ThreadStart = New ThreadStart(AddressOf workerthreadmethod)
Dim t As Thread = New Thread(worker)
t.Start()
MessageBox.Show("Wait for a while for the thread to start.")
MessageBox.Show(t.ThreadState.ToString())
t.Abort()
MessageBox.Show(t.ThreadState.ToString())
t.Join()
MessageBox.Show(t.ThreadState.ToString())
當然,在調用Abort方法后,線程并不是立刻終止,要等線程的所有finally快中的代碼完成后才會完全終止. 所以在主線程中可以用Join方法來同步,當線程還未完全終止時,t.Join()將處于等待,直到t線程完全結束后再繼續執行后面的語句。
Abort方法是會導致線程跳出一個異常錯誤的,你需要在代碼中捕獲該異常。下面是一個比較完整的VB.NET線程例子:
Imports System
Imports System.Threading
Public Class MyTestApp
Public Shared Sub Main()
Dim t As New Thread(New ThreadStart(AddressOf MyThreadMethod))
'Start the thread
t.Start()
MsgBox("Are you ready to kill the thread?")
'Kill the child thread and this will cause the thread raise an exception
t.Abort()
' Wait for the thread to exit
t.Join()
MsgBox("The secondary thread has terminated.")
End Sub
Shared Sub MyThreadMethod()
Dim i As Integer
Try
Do While True
Thread.CurrentThread.Sleep(1000)
Console.WriteLine("This is the secondary thread running.")
Loop
Catch e As ThreadAbortException
MsgBox("This thread is going to be terminated by the Abort method in the Main function")
End Try
End Sub
End Class
Thread.Abort()方法用來永久銷毀一個線程,而且將拋出ThreadAbortException異常。使終結的線程可以捕獲到異常但是很難控制恢復,僅有的辦法是調用Thread.ResetAbort()來取消剛才的調用,而且只有當這個異常是由于被調用線程引起的異常。因此,A線程可以正確的使用Thread.Abort()方法作用于B線程,但是B線程卻不能調用Thread.ResetAbort()來取消Thread.Abort()操作。
這個沒法做到。原因
1)當你將方法排入線程池隊列后,此方法在有線程池線程變得可用時執行。
2)線程池中某個線程的可用與不可用,是由.net 后臺決定,用戶程序無法控制的
3)正如你觀察到的:線程啟動的時間不同,有快有慢,這恰恰說明線程池起作用了:線程池的調度試圖讓程序響應達到最佳。
Sub Main()
Dim thr As Thread
For Pi As Integer=0 To 4 //啟用5線程
MulParams =Pi vbTab sFile vbTab dFile vbTab 1 vbTab DelN vbTab cr vbTab cg vbTab cb vbTab IndexI
GlobalParamas(pi)=MulParams .Split(vbTab)
thr=New Thread(AddressOf MyMulThreadCaller)
thr.Start() //啟動多線程進程
Application.DoEvents
Next
End Sub
Public?Class?Form1
Public?Class?SquareClass?'把多線程調用的函數封裝到類中,通過類事件返回
Public?Value?As?Double
Public?Square?As?Double
Public?Event?ThreadComplete(ByVal?Square?As?Double)
Public?Sub?CalcSquare()
Square?=?Value?*?Value
RaiseEvent?ThreadComplete(Square)
End?Sub
End?Class
Dim?WithEvents?oSquare?As?SquareClass
Private?Sub?Button1_Click(sender?As?Object,?e?As?EventArgs)?Handles?Button1.Click?'多線程返回值測試,當線程運行完成激發事件
oSquare?=?New?SquareClass()
Dim?t?As?New?Threading.Thread(AddressOf?oSquare.CalcSquare)
oSquare.Value?=?30
t.Start()
End?Sub
Sub?SquareEventHandler(ByVal?Square?As?Double)?Handles?oSquare.ThreadComplete?'響應事件函數
MsgBox("The?square?is?"??Square)
End?Sub
End?Class
名稱欄目:vb.net線程池例子 vb6 線程
URL鏈接:http://vcdvsql.cn/article24/ddcddce.html
成都網站建設公司_創新互聯,為您提供Google、App設計、品牌網站設計、做網站、軟件開發、小程序開發
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯