Reputation: 1879
I have an application where I list all the files from the folder selected. And I have a class called FileManager which contains, AsyncBindingList which is connected to my listBox on the form. here is the code,
public class frmWriter : Form
{
FileManager filemanager;
public frmWriter()
{
this.listBoxFilesFolder.DataSource = fileManager.FilesFolderList;
}
private void btnAddFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog FolderDialog = new FolderBrowserDialog();
FolderDialog.ShowNewFolderButton = false;
if (FolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//if I call this function in the following way, My application will not give
//any response to user mouse click.
filemanager.AddFileFolder(FolderDialog.SelectedPath);
}
}
}
public class FileManager
{
AsyncBindingList<string> FilesFolderList;
public FileManager()
{
FilesFolderList = new AsyncBindingList<string>();
}
public void AddFileFolder(string FolderSelected)
{
string[] Files = Directory.GetFiles(FolderSelected);
//List<string> ValidFiles = new List<string>();
foreach (string file in Files)
{
if (ValidateFile(file))
{
//Do some work
}
}
string[] Folders = Directory.GetDirectories(FolderSelected);
foreach (string folder in Folders)
GetFilesFromFolder(folder);
FilesFolderList.Add(FolderSelected);
}
private bool ValidateFile(string FilePath)
{
//This Function takes time to validate the file
return true;
}
}
What is this best way to call this method: filemanager.AddFileFolder, so UI, always resposive to mouse clicks.
if you have any code or any weblinks please post.
Thank you, Harsha
Upvotes: 0
Views: 306
Reputation: 11598
There are only two rules to using AsyncBindingList:
instantiate the AsyncBindingList on the UI thread update the AsyncBindingList ( via one of its Add/AddNew/Insert/Delete/Clear methods ) on the background thread. AsyncBindingList
You'll need to implement a Thread (or BackgroundWorker for the add method:
public class FileManager
{
public AsyncBindingList<string> FilesFolderList = new AsyncBindingList<string>();
private BackgroundWorker bw = new BackgroundWorker();
public FileManager()
{
bw.DoWork += GetFiles;
}
public void GetFiles(string startFolder)
{
bw.RunWorkerAsync(startFolder);
}
private void GetFiles(object sender, DoWorkEventArgs e)
{
var startFolder = e.Argument as string;
if (startFolder == null)
{
e.Cancel = true;
return;
}
var files = Directory.GetFiles(startFolder);
var validFiles = Array.Find(files, ValidateFile);
var folders = Directory.GetDirectories(startFolder);
var folderFiles = Array.ForEach(folders, GetFilesFromFolder);
FilesFolderList.Add(startFolder);
}
private List<string> GetFilesFromFolder()
{
return new List<string>();
}
private bool ValidateFile(string FilePath)
{
//This Function takes time to validate the file
return true;
}
Upvotes: 1