It seems a random chance that I will get a cross thread exception upon execution of my win forms application. Here's how I'm trying to manage it:
private void ToOutput(string s)
{
if (!this.IsHandleCreated)
this.CreateHandle();
if (FormOutputArea.InvokeRequired)
{
FormOutputArea.Invoke(new Action(delegate ()
{
FormOutputArea.AppendText(s + Environment.NewLine);
}));
}
else
{
FormOutputArea.AppendText(s + Environment.NewLine);
}
}
It appears InvokeRequired
is not always accurate. I tried BeginInvoke
with the same result.
EDIT: Even when I check IsHandleCreated
and InvokeRequired
using breakpoints they are set to true, yet the else
branch of the condition is executed.
Here's a screenshot showing where the exception is now thrown: