简体   繁体   中英

Invoke ToolStripMenuItem

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.

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"));
});

You are trying to access the menu item from a thread rather than the main thread, so try out this code:

MethodInvoker method = delegate
{
    toolStrip.DropDownItems.Add(new ToolStripItemEx("start"));
};

if (ToolStripMenu.InvokeRequired)
{
    BeginInvoke(method);
}
else
{
    method.Invoke();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM