Reputation: 783
I am learning to implement async/await on one of my task which takes a long time to complete. Once the task is completed, it should update the DGV.
private async void frmA_DragDrop(object sender, DragEventArgs e)
{
// Some codes to accept dropped files
// Run task asynchronously
Task<DataTable> task = Task.Run(() => PDF.CheckPDFs(Files, tblPDFs));
dgvPDF.DataSource = await task;
}
I found that after the task is completed, it is not updating the DGV. So, I added the InvokeRequired bit to manually update the table and also to prevent cross-thread exception.
// Update UI
if (dgvPDF.InvokeRequired)
{
dgvPDF.Invoke((MethodInvoker)(() => { dgvPDF.Refresh(); }));
}
else
{
dgvPDF.Refresh();
}
I also have a separate event handler which highlights the row red is a file is invalid:
private void dgvPDF_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
if (dgvPDF["Pages",e.RowIndex].Value.ToString() == "0")
dgvPDF.Rows[e.RowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.MistyRose;
}
What happened is that the RowAdded event handler is not triggered at all. If I made the code synchronous i.e removing await/async and invoke, everything works fine except with the UI freezing
My question is using InvokedRequired the correct way to update the UI in async await? What can I do to fix this issue?
Upvotes: 0
Views: 1134
Reputation: 133
no, you don't have to "invoke", the context will switch back after async method call complete, i.e., the statements after await will get executed in UI thread.
Upvotes: 1