I have this code (thanks to those that have been helping so far)
It searches through a directory and all subdirectories looking for a file names.
Files.Clear(); //BindingList<FileInfo> Datasource for a datagridview
Task.Factory.StartNew( () =>
{
DirectoryInfo dir = new DirectoryInfo(MainFolder);
foreach(var file in dir.EnumerateFiles("*" + textBox1.Text + "*.doc?", SearchOption.AllDirectories).Take(200))
{
this.BeginInvoke( new Action(() =>
{
Files.Add(file);
}));
}
});
The problem is if I set textBox1.text to something I know there is only 1 of, it adds it to Files 4 times. I tried break pointing it to be certain it wasn’t in how I was displaying it.
I compared the 4 objects to each other, they are identical. When I open up the search criteria a little and get 5 results, some of them are 1 some are doubles some triples. so there are 5 unique results but there is a total of about 10-12.
What am I doing wrong?
Use Invoke.
Your lambda is capturing the variable file which is being mutated. You are not only getting duplicates, you are also missing files.