Invoke ToolStripMenuItem

Zain Ali picture Zain Ali · Aug 22, 2011 · Viewed 7.2k times · Source

I'm trying to figure out if there's a way to Invoke ToolStripMenuItem.

For example,I am calling a web service(ASynchrously) when result is returned.i populate drop down items according to result,(In call back method)

 ToolStripMenuItem.DropDownItems.Add(new ToolStripItemEx("start"));

but I get exception

Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

There is no invoke function associated with the toolstrip item, Is there another way I can do this? Am I trying to do this the completely wrong way? Any input would be helpful.

Answer

Jalal Said picture Jalal Said · Aug 22, 2011

You are trying to execute code that rely on control main thread in another thread, You should call it using Invoke method:

toolStrip.Invoke(() =>
{
    toolStrip.DropDownItems.Add(new ToolStripItemEx("start"));
});

When accessing controls members/methods from a thread that is different from thread that the control originally created on, you should use control.Invoke method, it will marshal the execution in the delegate of invoke to the main thread.

Edit: Since you are using ToolStripMenuItem not ToolStrip, the ToolStripMenuItem doesn't have Invoke member, so you can either use the form invoke by "this.Invoke" or your toolStrip its parent "ToolStrip" Invoke, so:

toolStrip.GetCurrentParent().Invoke(() =>
{
    toolStrip.DropDownItems.Add(new ToolStripItemEx("start"));
});