[RESOLVED] [2.0] BackgroundWorker not finishing correctly
I'm using a background worker to search for files and put them in a list box. This works fine, but i want to be able to cancel the search and restart it according to user input.
In my DoWork event for the BGworker i call my search function, which includes logic to watch for the cancellationpending being true.
I know my search function does exit correctly, and early if a cancelAsync is called on the worker since i put a breakpoint in the line below that function. I've also tested it with a messagebox after it.
I also put a messagebox / breakpoint in the runworkercompleted event, but this doesn't get called for some reason. It should do once the worker is out of the DoWork method shouldn't it (or at least soon after)???
In my UI when a textbox's text changes i do a cancelASync call, then loop until the IsBusy flag is false. This is what hangs the application, indicating that the BGWorker isn't finished.
The thing that's confusing me is that the DoWork event code DOES finish (the test messagebox is the last thing there).
Why is the RunWorkerCompleted event not being triggered, and why isn't the IsBusy member not being set to false when the DoWork stuff returns?
Thanks for any help.
DoWork event method
Code:
private void FileSearcher_DoWork(object sender, DoWorkEventArgs e)
{
FindFiles(e.Argument);
MessageBox.Show("Done finding files"); //Gets shown as expected
}
RunWorkerCompleted event method
Code:
private void FileSearcher_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("finished"); //Never gets shown
}
UI event method code to cancel and restart the BGWorker
Code:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
FileSearcher.CancelAsync();
if (txtSearch.Text.Length == 0)
return;
FoundItemsQueue.Clear();
int CursorPos = txtSearch.SelectionStart;
lstFound.Items.Clear();
txtSearch.SelectionStart = CursorPos;
if (txtSearch.Text.Contains("/"))
return;
while (FileSearcher.IsBusy); //Hangs here
FileSearcher.RunWorkerAsync(txtSearch.Text);
}
Re: [2.0] BackgroundWorker not finishing correctly
Found the problem! It seems a BGWorker isn't totally in a seperate thread, so it's finished event wasn't fireing (so the IsBusy variable i was checking would never be changed).
I solved the peoblem by changing my while loop to include 'Application.DoEvents()'
Now.... how do i give myself reputation points?? :P