“卡死”是一个非常主观的描述,如果你要让主线程杀掉卡死的线程,那么你必须给“卡死”做出准确的定义。
成都创新互联公司专业IDC数据服务器托管提供商,专业提供成都服务器托管,服务器租用,多线服务器托管,多线服务器托管,成都多线服务器托管等服务器托管服务。
什么是卡死?30秒没有响应就是卡死?那么“没有响应”的定义又是什么?
你给出这些条件以后,杀掉一个线程就不难。Abort方法,Dispose方法,都可以。
右击工具箱/部件/WindowsMediaPlayer
//类模块Mmedia
Option Explicit
'-----------------------------------------------------
' Name : MMedia.cls
' Author : Peter Wright, For BG2VB4 BG2VB5
'
' Notes : A multimedia class, which when turned
' : into an object lets you load and play
' : multimedia files, such as sound and
' : video.
'-----------------------------------------------------
' -=-=-=- PROPERTIES -=-=-=-
' Filename Determines the name of the current file
' Length The length of the file (Read Only)
' Position The current position through the file
' Status The current status of the object (Read Only)
' Wait True/False...tells VB to wait until play done
' -=-=-=- METHODS -=-=-=-=-
' mmOpen Filename Opens the requested filename
' mmClose Closes the current file
' mmPause Pauses playback of the current file
' mmStop Stops playback ready for closedown
' mmSeek Position Seeks to a position in the file
' mmPlay Plays the open file
'-------------------------------------------------------------
' NOTES
' -----
'
' Open a file, then play it. Pause it in response to a request
' from the user. Stop if you intend to seek to the start and
' play again. Close when you no longer want to play the file
'--------------------------------------------------------------
Private sAlias As String ' Used internally to give an alias name to
' the multimedia resource
Private sFilename As String ' Holds the filename internally
Private nLength As Single ' Holds the length of the filename
' internally
Private nPosition As Single ' Holds the current position internally
Private sStatus As String ' Holds the current status as a string
Private bWait As Boolean ' Determines if VB should wait until play
' is complete before returning.
'------------ API DECLARATIONS -------------
'note that this is all one code line:
Private Declare Function mciSendString Lib "winmm.dll" _
Alias "mciSendStringA" (ByVal lpstrCommand As String, _
ByVal lpstrReturnString As String, ByVal uReturnLength As Long, _
ByVal hwndCallback As Long) As Long
Public Sub mmOpen(ByVal sTheFile As String)
' Declare a variable to hold the value returned by mciSendString
Dim nReturn As Long
' Declare a string variable to hold the file type
Dim sType As String
' Opens the specified multimedia file, and closes any
' other that may be open
If sAlias "" Then
mmClose
End If
' Determine the type of file from the file extension
Select Case UCase$(Right$(sTheFile, 3))
Case "WAV"
sType = "Waveaudio"
Case "AVI"
sType = "AviVideo"
Case "MID"
sType = "Sequencer"
Case Else
' If the file extension is not known then exit the subroutine
Exit Sub
End Select
sAlias = Right$(sTheFile, 3) Minute(Now)
' At this point there is no file open, and we have determined the
' file type. Now would be a good time to open the new file.
' Note: if the name contains a space we have to enclose it in quotes
If InStr(sTheFile, " ") Then sTheFile = Chr(34) sTheFile Chr(34)
nReturn = mciSendString("Open " sTheFile " ALIAS " sAlias _
" TYPE " sType " wait", "", 0, 0)
End Sub
Public Sub mmClose()
' Closes the currently opened multimedia file
' Declare a variable to hold the return value from the mciSendString
' command
Dim nReturn As Long
' If there is no file currently open then exit the subroutine
If sAlias = "" Then Exit Sub
nReturn = mciSendString("Close " sAlias, "", 0, 0)
sAlias = ""
sFilename = ""
End Sub
Public Sub mmPause()
' Pause playback of the file
' Declare a variable to hold the return value from the mciSendString
' command
Dim nReturn As Long
' If there is no file currently open then exit the subroutine
If sAlias = "" Then Exit Sub
nReturn = mciSendString("Pause " sAlias, "", 0, 0)
End Sub
Public Sub mmPlay()
' Plays the currently open file, from the current position
' Declare a variable to hold the return value from the mciSendString
' command
Dim nReturn As Long
' If there is no file currently open, then exit the routine
If sAlias = "" Then Exit Sub
' Now play the file
If bWait Then
nReturn = mciSendString("Play " sAlias " wait", "", 0, 0)
Else
nReturn = mciSendString("Play " sAlias, "", 0, 0)
End If
End Sub
Public Sub mmStop()
' Stop using a file totally, be it playing or whatever
' Declare a variable to hold the return value from mciSendString
Dim nReturn As Long
' If there is no file currently open then exit the subroutine
If sAlias = "" Then Exit Sub
nReturn = mciSendString("Stop " sAlias, "", 0, 0)
End Sub
Public Sub mmSeek(ByVal nPosition As Single)
' Seeks to a specific position within the file
' Declare a variable to hold the return value from the mciSendString
' function
Dim nReturn As Long
nReturn = mciSendString("Seek " sAlias " to " nPosition, "", 0, 0)
End Sub
Property Get Filename() As String
' Routine to return a value when the programmer asks the
' object for the value of its Filename property
Filename = sFilename
End Property
Property Let Filename(ByVal sTheFile As String)
' Routine to set the value of the filename property, should the programmer
' wish to do so. This implies that the programmer actually wants to open
' a file as well so control is passed to the mmOpen routine
mmOpen sTheFile
End Property
Property Get Wait() As Boolean
' Routine to return the value of the object's wait property.
Wait = bWait
End Property
Property Let Wait(bWaitValue As Boolean)
' Routine to set the value of the object's wait property
bWait = bWaitValue
End Property
Property Get Length() As Single
' Routine to return the length of the currently opened multimedia file
' Declare a variable to hold the return value from the mciSendString
Dim nReturn As Long, nLength As Integer
' Declare a string to hold the returned length from the mci Status call
Dim sLength As String * 255
' If there is no file open then return 0
If sAlias = "" Then
Length = 0
Exit Property
End If
nReturn = mciSendString("Status " sAlias " length", sLength, 255, 0)
nLength = InStr(sLength, Chr$(0))
Length = Val(Left$(sLength, nLength - 1))
End Property
Property Let Position(ByVal nPosition As Single)
' Sets the Position property effectively by seeking
mmSeek nPosition
End Property
Property Get Position() As Single
' Returns the current position in the file
' Declare a variable to hold the return value from mciSendString
Dim nReturn As Integer, nLength As Integer
' Declare a variable to hold the position returned
' by the mci Status position command
Dim sPosition As String * 255
' If there is no file currently opened then exit the subroutine
If sAlias = "" Then Exit Property
' Get the position and return
nReturn = mciSendString("Status " sAlias " position", sPosition, 255, 0)
nLength = InStr(sPosition, Chr$(0))
Position = Val(Left$(sPosition, nLength - 1))
End Property
Property Get Status() As String
' Returns the playback/record status of the current file
' Declare a variable to hold the return value from mciSendString
Dim nReturn As Integer, nLength As Integer
' Declare a variable to hold the return string from mciSendString
Dim sStatus As String * 255
' If there is no file currently opened, then exit the subroutine
If sAlias = "" Then Exit Property
nReturn = mciSendString("Status " sAlias " mode", sStatus, 255, 0)
nLength = InStr(sStatus, Chr$(0))
Status = Left$(sStatus, nLength - 1)
End Property
//窗体fm
Dim m As New Mmedia
Dim fn
Private Sub Command1_Click()
On Error GoTo r
dlg.ShowOpen
fn = dlg.Filename
m.mmOpen fn
r:
If Err Then MsgBox Err.Description
End Sub
Private Sub Command2_Click()
On Error GoTo rp
m.mmPlay
rp:
If Err Then MsgBox Err.Description
End Sub
Private Sub Command3_Click()
On Error GoTo rap
m.mmPause
rap:
If Err Then MsgBox Err.Description
End Sub
Private Sub Command4_Click()
On Error GoTo racp
m.mmStop
racp:
If Err Then MsgBox Err.Description
End Sub
vb.net中如何结束一个线程
一般而言,如果您想终止一个线程,您可以使用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()操作。
以记事本为例
Public Class Form1
Public Sub ShellAndWait(ByVal ProcessPath As String)
Dim objProcess As System.Diagnostics.Process
Try
objProcess = New System.Diagnostics.Process()
objProcess.StartInfo.FileName = ProcessPath
objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
objProcess.Start()
objProcess.WaitForExit()
objProcess.Close()
Catch
MessageBox.Show("无法执行文件 " ProcessPath, "错误")
End Try
End Sub
'监视程序就可以了,若果监视别的窗体的话,用SPY++ 找到句柄,配合FindWindowEx,SendMessage根据其属性做
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ShellAndWait("Notepad.exe")
MessageBox.Show("笔记本被关闭后我才会出现")
End Sub
End Class