开发者

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 associat开发者_如何学运维ed 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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜