I have the following method that loads the data to DataGridView in a separate function. When I call the method in a button click, first two methods runs without hanging the windows since they dod not have any UI updates.
private async void btnSearch_Click(object sender, EventArgs e)
{
btnFolder.Enabled = false;
btnSearch.Enabled = false;
btnStop.Enabled = true;
try
{
var foldersTask = Task.Run(() => GetAccessibleDirectories(txtFolderPath.Text, chkSubFolders.Checked));
var folders = await foldersTask;
var BF = await Task.Run(() => getFolderdetails(folders));
await Task.Run(() => this.BeginInvoke(new Action(() => loadFoldersToGrid(BF)))); // Runs on UI thread
}
finally
{
btnFolder.Enabled = true;
btnSearch.Enabled = true;
btnStop.Enabled = false;
}
}
But when it starts running 'loadFoldersToGrid,' the window freezes (it backs to normal once it is loaded completely.). I don't understand it why.
private async void loadFoldersToGrid(BrowserFolders BF)
{
int i = 0;
long MBcon = 1048576;
long MB, Total = 0;
dgFolders.Rows.Clear();
dgFolders.Rows.Add(BF.folders.Count);
foreach (var rec in BF.folders)
{
dgFolders.Rows[i].Cells[0].Value = i;
dgFolders.Rows[i].Cells[1].Value = rec.folderPath;
dgFolders.Rows[i].Cells[2].Value = rec.fileCount;
long folderSize = GetFolderSize(rec.folderPath);
string megabytes = (folderSize / MBcon).ToString("F1");
dgFolders.Rows[i].Cells[3].Value = megabytes;
dgFolders.Rows[i].Cells[4].Value = rec.fileCreated.ToString("MM/dd/yyyy");
Total = Total + folderSize;
i += 1;
}
txtFolderCount.Text = BF.folders.Count.ToString();
txtSize.Text = string.Format("{0:N0} MB", Total / MBcon);
}
Any help ? tasks to not helping here.