I need some help fixing a cross-thread exception. I am using Invoke which usually solves this issue, but for some reason it is not wokring:
void paintTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Invoke(new InvalidateFromSepThreadDel(InvalidateFromSepThread));
}
delegate void InvalidateFromSepThreadDel();
void InvalidateFromSepThread()
{
TailGraph.Invalidate();
}
The exception is thrown on the Invoke:
$exception {“Cross-thread operation not valid: Control ‘XTailGraph’
accessed from a thread other than the thread it was created
on.”} System.Exception {System.InvalidOperationException}
Invokewill marshal back the thread that control (the one who’s Invoke method is being used) was created on. Make sure the other control was also created on said thread — that is, make sure one control wasn’t created on “the wrong thread” to begin with.Also, since no target for
Invokewas specified then it will be thethis.Invokeof the containing object/class — which might not be appropriate.(Or as Hasan Khan pointed out, consider the WinForms timer… the callback will always run in the thread the timer was created on, in that case.)
Happy coding.