Threading.Timer的疑惑
有下边的一段代码,在button1里启动了Threading.Timer后,发现竟然停止不了了。检测对象时发现Timer对象已经销毁,但getsize()里的代码竟然还在执行。
这个是否有别的问题?
Private RemotFile As String = "" '远程文件路径 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim n As New System.IO.FileInfo(MusicFile.Text) fileName = MusicFile.Text FileSize = n.Length Dim b As New Threading.Thread(AddressOf Upload) b.IsBackground = True b.Start() Dim GetSizeThread As Thread GetSizeThread = New Threading.Thread(AddressOf TestThreadTimer) GetSizeThread.IsBackground = True GetSizeThread.Start() End Sub Private ThreadTimer As System.Threading.Timer = Nothing Public Sub TestThreadTimer() ThreadTimer = New System.Threading.Timer(New TimerCallback(AddressOf Me.GetSize), Nothing, 0, 200) End Sub Private FileSize As Long = 0 Private fileName As String = "" Private Sub Upload() Dim ftp As New FTPUpDown ftp.FtpServerIP = "ftp://www.aaa.com/" ftp.FtpUserName = "aaa" ftp.FtpPassword = "aaa" ftp.Upload(fileName, RemotFile) Try Threading.Thread.CurrentThread.Join() Catch ex As Threading.ThreadAbortException Err.Clear() Finally Threading.Thread.CurrentThread.Abort() End Try End Sub Private Sub GetSize() Try Dim a As New FTPUpDown a.FtpServerIP = "ftp://www.aaa.com/" a.FtpUserName = "aaa" a.FtpPassword = "aaa" Dim t As Long = a.GetFileSize(RemotFile) SetText(Status, ((t / FileSize) * 100).ToString("00.00") & "%" & Now) SetPro(FileSize, t) If t >= FileSize Then If Not ThreadTimer Is Nothing Then ThreadTimer.Dispose() ThreadTimer = Nothing End If End If Threading.Thread.CurrentThread.Join() Catch ex As Threading.ThreadAbortException Err.Clear() Finally Threading.Thread.CurrentThread.Abort() End Try End Sub Delegate Sub SetProV(ByVal m As Integer, ByVal v As Integer) Private Sub SetPro(ByVal m As Integer, ByVal v As Integer) If Me.ProgressBar1.InvokeRequired Then Dim d As New SetProV(AddressOf SetPro) Me.Invoke(d, New Object() {m, v}) Else ProgressBar1.Maximum = m ProgressBar1.Value = v End If End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click If Not ThreadTimer Is Nothing Then ThreadTimer.Dispose() ThreadTimer = Nothing End If Dim a As New FTPUpDown a.FtpServerIP = "ftp://www.aaa.com/" a.FtpUserName = "aaa" a.FtpPassword = "aaa" Dim b As New Thread(AddressOf DeleteFile) b.IsBackground = True b.Start() End Sub Private Sub DeleteFile() Dim a As New FTPUpDown a.FtpServerIP = "ftp://www.aaa.com/" a.FtpUserName = "aaa" a.FtpPassword = "aaa" If a.Delete(RemotFile) = True Then SetText(Status, "Finished!") Else SetText(Status, "Failed.") End If Try Threading.Thread.CurrentThread.Join() Catch ex As Threading.ThreadAbortException Err.Clear() Finally Threading.Thread.CurrentThread.Abort() End Try End Sub
Threading.Timer只执行了一次
http://www.cnblogs.com/shang20017/archive/2009/03/16/1413798.html
[解决办法]
不奇怪,实践证明Abort并不能保证线程一定被终止,所以我经常在程序结束时才Abort,就这样也不可靠,所以对于带线程的程序,结束时除了me.close外,还要把application.exit以及久违的End一鼓脑全加上