vb點(diǎn)虐 中如何結(jié)束一個(gè)線程
創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都做網(wǎng)站、成都網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿(mǎn)足客戶(hù)于互聯(lián)網(wǎng)時(shí)代的蔚縣網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
一般而言,如果您想終止一個(gè)線程,您可以使用System.Threading.Thread類(lèi)的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())
當(dāng)然,在調(diào)用Abort方法后,線程并不是立刻終止,要等線程的所有finally快中的代碼完成后才會(huì)完全終止. 所以在主線程中可以用Join方法來(lái)同步,當(dāng)線程還未完全終止時(shí),t.Join()將處于等待,直到t線程完全結(jié)束后再繼續(xù)執(zhí)行后面的語(yǔ)句。
Abort方法是會(huì)導(dǎo)致線程跳出一個(gè)異常錯(cuò)誤的,你需要在代碼中捕獲該異常。下面是一個(gè)比較完整的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()方法用來(lái)永久銷(xiāo)毀一個(gè)線程,而且將拋出ThreadAbortException異常。使終結(jié)的線程可以捕獲到異常但是很難控制恢復(fù),僅有的辦法是調(diào)用Thread.ResetAbort()來(lái)取消剛才的調(diào)用,而且只有當(dāng)這個(gè)異常是由于被調(diào)用線程引起的異常。因此,A線程可以正確的使用Thread.Abort()方法作用于B線程,但是B線程卻不能調(diào)用Thread.ResetAbort()來(lái)取消Thread.Abort()操作。
public class threadclass
{
public int a;
public void threadmethod()
{
//use a;
}
}
...
threadclass tc = new ....
tc.a = 10;
Thread t = new ThreadStart(tc.threadmethod);
t.Start
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() //啟動(dòng)多線程進(jìn)程
Application.DoEvents
Next
End Sub