我正在研究扫描用户定义的目录并提取所有文件扩展名的实用程序。
在下面提到的按钮事件中,我开始执行所有扫描的线程,但是我希望代码在'A点'暂停或停止,直到该线程完成其工作,而现在它启动线程并在'A点'。如何停止代码继续?当线程启动时挂起其他线程Vb.Net
Private Sub Btn_Extract_Click(sender As Object, e As EventArgs) Handles Btn_Extract.Click
Dim eventobject As New EventsandFunctions
eventobject.FilesCounter = 0
eventobject.DirectoryCounter = 0
AddHandler eventobject.FilesScanned, AddressOf eventobject.FilesScannedCounterIncrease
AddHandler eventobject.DirectoryScanned, AddressOf eventobject.DirectoryScannedCounterIncrease
If TxtB_SaveFilePath.Text = Nothing Or TxtBx_DirectoryToScan.Text = Nothing Then
MessageBox.Show("Scan Path, Output File Path or Both Missing", "Error")
Else
ThreadFileScanning.Start(eventobject) 'Thread Starts here--<Point A>
If ChckB_RemoveDot.Checked Then
eventobject.WriteExtentionsToFileWithoutDot(TxtB_SaveFilePath.Text)
Else
eventobject.WriteExtentionsToFile(TxtB_SaveFilePath.Text)
End If
MessageBox.Show("Operation Completed Successfully." & vbCrLf & vbCrLf & "Total Directory Scanned: " & eventobject.DirectoryCounter & vbCrLf & "Total Files Scanned: " & eventobject.FilesCounter, "Completion Notification")
Lbl_FileNames.Text = "Scanning & Writing Completed"
End If
Process.Start("notepad.exe", TxtB_SaveFilePath.Text)
End Sub
以下是这就是所谓的线程功能:
Public Sub RecursivelyScanFiles(ByVal Path As String, ByVal ObjectDb As DialogueBox)
If Path <> Nothing Then
For Each File In GetFiles(Path)
If File.Length < 260 Then
If System.IO.Path.HasExtension(File) = True Then
Extentions.Add(System.IO.Path.GetExtension(File).ToLower)
End If
ObjectDb.settext(File) 'Cross-Thread call Through a Delegate
ObjectDb.Refreshlabel() 'Cross-Thread call Through a Delegate
RaiseEvent FilesScanned(Me, EventArgs.Empty)
End If
Next
End If
If Path <> Nothing Then
For Each SubDir In GetDirectories(Path)
If SubDir.Length < 248 Then
Try
RaiseEvent DirectoryScanned(Me, EventArgs.Empty)
RecursivelyWriteToFile(SubDir, ObjectDb)
Catch ex As UnauthorizedAccessException
Continue For
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End If
Next
End If
End Sub
你在问错误的问题,代码有太多的问题需要刺探答案。使用BackgroundWorker类可避免发生最基本的错误,其RunWorkerCompleted和ProgressChanged事件可帮助您陷入成功之坑。 – 2014-09-24 15:09:36
我在MSDN上阅读了关于BackgroundWorker的内容,但我认为使用委托更容易。你建议BackgroundWorker? – Rehan 2014-09-24 15:13:04
我同意@HansPassant。在可能的情况下,应该使用后台工作者,但由于线程问题,我已经给出了一个应该与线程一起工作的答案(如果我正确理解问题) – Grahamvs 2014-09-24 15:23:14