Trying to perform a heavy task and keep UI updated. Using async/await, I would like to refresh some controls once the processing is complete. Basically code looks like this:
private async void btn_Click(object sender, EventArgs e)
{
// progress reporter
var progressHandler = new Progress<string>(value =>
{
lblProgress.Text = value.ToString();
});
var progress = (IProgress<string>)progressHandler;
// async method call
await MyTask(progress); // this will update a list with data (myList)
// custom method that sets grid data source and rebinds the grid:
// executed but grid NOT refreshed although this runs in Main thread
// -> why?
gridHelper.Reload(myGrid, myList);
// Reload(myGrid) above basically does this:
// grid.DataSource = myList;
// grid.ResetBindings();
lblProgress.Text = string.Empty; // works!
SetControlsEnabled(true); // works! (updates some buttons status)
}
private async Task MyTask(IProgress<string> progress)
{
await Task.Run(() =>
{
// some pre-processing
// ...
while (condition)
{
// time-consuming processing
// ...
// report progress
progress.Report("some progress done...");
}
}).ConfigureAwait(false);
}
Most of it works. Task is performed, labels are updated, progress is reported and UI is not blocked. But the grid is not updated, although it is running on Main thread and after async task completes. If I call that exact same grid refresh code in another event handler, it works.
I already read extensive documentation about this (special thanks to Stephen Stephen Cleary), and I think I could get this working using Thread classes. However I wonder why isn't the grid updated?