If you run the following code then close the form you get a ObjectDisposedException "Cannot access a disposed object." despite the guard clause in the commented line (26).
What is a correct way to detect that a Form has been Dispose()d to prevent this exception from happening?
using System;
using System.Threading;
using System.Windows.Forms;
namespace DisposeExample
{
static class Program
{
[STAThread]
static void Main()
{
var handleCreated = new ManualResetEvent(false);
Form form = null;
ThreadStart createForm = () =>
{
form = new Form();
form.Show();
handleCreated.Set();
Application.Run(form);
};
ThreadStart updateData = () =>
{
while (true)
{
if (!form.IsDisposed) // this doesn't prevent ObjectDisposedException
// if (form.Visible) // this doesn't prevent ObjectDisposedException
form.Invoke((MethodInvoker)(() => form.Text = form.Text == "A" ? "B" : "A"));
}
};
var updateDataThread = new Thread(updateData);
updateDataThread.IsBackground = true;
new Thread(createForm).Start();
handleCreated.WaitOne();
updateDataThread.Start();
}
}
}