This problem puzzled me for a while, I think I understand the issue now, but I cant figure out the implementation detail to fix it.
I have a background thread running that has a function that repeatedly gets a datagridview cell contents by calling code via Invoke(). The problem occurs when the user clicks on the form close. I get an "Object disposed exception" when trying to access the datagridview on that form. That makes sense, so I added a line to not call Invoke if the control already has been disposed. This solution doesnt work however. What must be happening is that I have a race condition where I check the disposed flag is false, but at that exact point the main gui thread runs and closes the form and disposes the DGV.
public delegate object dlgMethod(Control ctrl, string methodName, object param1, object param2, object param3, object param4);
public object method(Control ctrl, string methodName, object param1 = null, object param2 = null, object param3 = null, object param4 = null)
{
object retVal = null;
if (ctrl.InvokeRequired)
{
if (!ctrl.IsDisposed)
retVal = ctrl.Invoke(new dlgMethod(method), new object[] { ctrl, methodName, param1, param2, param3, param4 });
return retVal;
}
else
{ // code snipped
I am guessing there are 2 ways to fix this ?
1) I could try and make the ctrl.isDisposed test and the Invoke atomic, there is maybe a way to do this with a lambda call, but I cant figure out the syntax ?
or 2) Use EventWaitHandler class to improve the thread synchronizing so that the exception cant happen ?
Would greatly appreciate any example how to fix up the broken code above please ?
Regards Geoff