I am loading docs in a datagridview from a parallel thread using the code below:
inside a block Task.Run(() => {});
When I close the form I get ObjectDisposedException Cannot access a disposed object.
Looks like the if (IsDisposed || Disposing)
fails and the code attempts to add a row and in the meantime Disposing has became true.
I could catch this exception but it is dirty.
Adding a flag enabled when closing the form to check if the form has been closed does not work as well. It seems to behave the same way as this.Disposing
Adding a Thread.Sleep(5);
before if (this.IsDisposed || this.Disposing)
seems enough to avoid the exception to be raised though I am not sure if it could be raised if unlucky enough.
What would probably be the best practice to avoid this issue ?
foreach (var doc in docList)
{
if (this.InvokeRequired)
{
if (IsDisposed || Disposing || dgv.IsDisposed || dgv.isposing) return;
this.Invoke(new MethodInvoker(() => { dgv.Rows.Add(doc.Name); }));
}
}