So I've searched this and other sites and I have found some hints that I think should solve my problem, but for the life of me I can't get it to work. Here's an overview. I'm working on a VB.net program that finds and lists the timestamps of files as well as their exif info if they are JPG files and populates a file list. Things work fine unless a directory has many JPG files so I decided to put the code that reads the files info into a backgound worker. My file list populate routine (lstFileList_Populate) calls the BackgroundWorker1.RunWorkerAsync. When the program starts the lstFileList_Populate gets called and when I change directory it gets called again. When it gets called the second time the BackgroundWorker1 is busy so I try to cancel it, but it never cancels. Here are some excerpts from my code.
The lstFileList_Populate:
Private Sub lstFileList_Populate(ByVal strFileFilters As String)
BackgroundWorker1.WorkerReportsProgress = True
If (BackgroundWorker1.IsBusy) Then
BackgroundWorker1.CancelAsync()
While BackgroundWorker1.CancellationPending
Threading.Thread.Sleep(1000)
End While
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
The Backgroundworker1_Dowork:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
' Bunch of variables defined here for the actual work
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
BackgroundWorker1.Dispose()
Else
' Since code was never exiting I put this second check for CancellationPending here,
' and again in the for loop below but I believe it's not necessary.
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
BackgroundWorker1.Dispose()
Else
For Each strAFileName In My.Computer.FileSystem.GetFiles(Directory.GetCurrentDirectory())
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
BackgroundWorker1.Dispose()
Exit Sub
End If
' The evaluation of each file gets done here in a rather long section of code
End If
End If
End Sub
So when the lstFileList_Populate gets called the second time the code will stay in this while loop
While BackgroundWorker1.CancellationPending
Threading.Thread.Sleep(1000)
End While
and will never exit and, of course, if I take out the above code I get the error message that the background worker is busy. What am I doing wrong????
P.S. BTW, I don't have any training in VB or VB.net other than what I've picked up online and trained myself. I've written a few programs in VB and this is my first crack at .net so my knowledge is limited. I have spent hours researching this, but it still eludes me.