I have a C# Windows Form application that contains a menu with this event:
private void createMenuItem_Click(object sender, EventArgs e)
{
canvas.Layer.RemoveAllChildren();
canvas.Controls.Clear();
createDock();
}
I would like to provide the user with the opportunity to fire this event through another menu option that pulls up a timer.
My timer looks like this:
private void transfer_timer()
{
System.Timers.Timer Clock = new System.Timers.Timer();
Clock.Elapsed += new ElapsedEventHandler(createMenuItem_Click);
Clock.Interval = timer_interval;
Clock.Start();
}
When I do this the resulting error message is:
createDock – Cross-thread operation not valid: Control ” accessed from a thread other than the thread it was created on.
What am I doing wrong?
Don’t do that. 🙂 Factor it out more like this …
That will give you much more clear and much more maintainable code. Your timer is not selecting a menu, it’s doing the work that’s the same as if the menu had been selected.
Per comment: You’re welcome. Glad to help! Here’s a good primer on cross thread marshaling (short read, good examples). But, basically BeginInvoke is taking a delegate (the MethodInvoker) and executing it asynchronously on the thread that the control was created on. In this case, it’s a non-blocking, fire and forget message across threads (i.e. I don’t wait for a return and I don’t call EndInvoke to get a return). If you really want to get in-depth with this, Chris Sells book on Winforms is a great resource.