Invoke ToolStripMenuItem

I am trying to figure out if there is a way to call ToolStripMenuItem.

For example, I call a web service (ASynchrously) when the result is returned. Fill out the dropdown items according to the result, (in callback mode)

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

but i get an exception

Working with multiple threads is invalid: the control '' is accessible from a thread other than the thread in which it was created.

There is no call function associated with the dashboard item . Is there any other way I can do this? Am I trying to do this completely wrong? Any input would be helpful.

+8
c # invoke winforms user-controls contextmenustrip
source share
2 answers

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

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

When accessing controls / methods from a stream other than the stream that the control was originally created, you should use the control.Invoke method, it will marshal the execution of the call deletion to the main stream.

Edit: Since you are using ToolStripMenuItem not ToolStrip , ToolStripMenuItem does not have an Invoke member, so you can use the invoke form using this.Invoke "or your ToolStrip its parent element is" ToolStrip "Call, therefore:

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

You are trying to access a menu item from a stream, not the main stream, so try this code:

 MethodInvoker method = delegate { toolStrip.DropDownItems.Add(new ToolStripItemEx("start")); }; if (ToolStripMenu.InvokeRequired) { BeginInvoke(method); } else { method.Invoke(); } 
+4
source share

All Articles