Логика программы
Я делаю простой сигнатурный сканер вредоносных программ, который загружает местоположения файлов из файла. Для каждой строки в файле он попытается получить хэш md5. Каждая строка в файле - это абсолютное местоположение файла.
Для отображения прогресса я использую индикатор выполнения и фоновый рабочий.
Задача
Фоновый рабочий вообще не работает. Неважно, что я делаю и сколько раз я называю работником run asyn, он не запускается.
Код: для кнопки переключения
Private Sub btnToggleScan_Click(sender As Object, e As EventArgs) Handles btnToggleScan.Click
If isScanning = True Then
' if scanning, stop scanning
txtStatus.Text = "Status: Idle..."
btnToggleScan.Image = Image.FromFile("res/malware_scanner/rocket.png")
If bgWorker_Scanner.IsBusy Then
Try
bgWorker_Scanner.CancelAsync()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
isScanning = False
Else
' if not scanning, start scanning
txtStatus.Text = "Status: Scanning..."
btnToggleScan.Image = Image.FromFile("res/malware_scanner/loading_dark.gif")
If bgWorker_Scanner.IsBusy Then
Try
bgWorker_Scanner.RunWorkerAsync()
Catch ex As Exception
Me.Close()
End Try
End If
txtCalmDown.Text = "Feel free to do other work!"
isScanning = True
End If
End Sub
Код: для фонового работника
Private Sub bgWorker_Scanner_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker_Scanner.DoWork
' storage declares
Dim temp_hash_values As New List(Of String)() ' store malware hash per malware hash file
Dim hashFile_lineParts As String() ' store parts of packed/unpacked hash
Dim se_queryfile_hashes As New List(Of String)() ' store file hashes of search index query
' file operating declares
Dim file_bytes() As Byte
Dim file_bytes_size As Integer
Dim lineInFile As String
Dim lineBytes() As Byte
Dim lineBytes_size As Integer
Dim totalRead_size As Integer
' declare file reader
Dim reader As StreamReader
' if quickscan, then get hash list
If scanType = "Quick" Then
Dim md5hash As String
reader = My.Computer.FileSystem.OpenTextFileReader(Application.StartupPath & "/data/win_searchIndex_results.list")
' get file bytes
file_bytes = File.ReadAllBytes(Application.StartupPath & "/data/win_searchIndex_results.list")
' get size of file bytes in integer
file_bytes_size = file_bytes.Length
Do
lineInFile = reader.ReadLine
If Not String.IsNullOrEmpty(lineInFile) Then
' get line bytes
lineBytes = System.Text.Encoding.ASCII.GetBytes(lineInFile)
' get line bytes size in integer
lineBytes_size = lineBytes.Length
' add line bytes size to total size read
totalRead_size += lineBytes_size
Try
md5hash = Hasher.Getmd5(lineInFile)
se_queryfile_hashes.Add(md5hash.ToString)
' testing
' Dim temp As String = totalRead_size.ToString & " \ " & file_bytes_size.ToString
' MsgBox(md5hash.ToString)
Catch ex As Exception : End Try
End If
bgWorker_Scanner.ReportProgress(CInt(totalRead_size / file_bytes_size) * 100)
check_bgWorkerCancelled()
Loop Until lineInFile Is Nothing
End If
' clean temporary storage after each file operation
temp_hash_values.Clear() : Erase hashFile_lineParts : Erase file_bytes : file_bytes_size = 0 : lineInFile = Nothing : Erase lineBytes : lineBytes_size = Nothing
End Sub
Дополнительный код
Я также проверяю, отменяется ли рабочий в каждом цикле цикла, чтобы убедиться, что при нажатии кнопки переключения рабочий не продолжает работать. Ниже приведен код для функции проверки:
' Method: To check is cancellation is pending
Private Sub check_bgWorkerCancelled()
' check if cancellation is pending
If bgWorker_Scanner.CancellationPending = True Then
' background worker cancel asynchronoous operating
If bgWorker_Scanner.IsBusy Then
bgWorker_Scanner.CancelAsync()
End If
isScanning = False
Try
' invoke to bypass illegal cross threading UI update
BeginInvoke(CType(Sub()
progressBar1.Value = 0
txtStatus.Text = "Cancelled"
txtCalmDown.Text = ""
btnToggleScan.Image = Image.FromFile(Application.StartupPath & "/res/malware_scanner/rocket.png")
End Sub, MethodInvoker))
Catch ex As Exception : End Try
Else
Exit Sub
End If
End Sub
Не могу понять, почему он не работает. Любая помощь приветствуется.
Вот скриншот для более подробной информации: