从单独的线程添加菜单项
我正在一个单独的线程中创建菜单项,并将它们添加到主线程中创建的菜单中。我正在使用 Invoke 来实现这一点。出现“值不在预期范围内”异常。
//creating new thread
Thread thread = new Thread(LoadRecentTasks);
thread.IsBackground = true;
thread.Start();
private void LoadRecentTasks()
{
EntryCollection recentEntries = Entry.GetRecentEntries(10);
foreach (Entry entry in recentEntries)
{
MenuItemPlus menuItem = new MenuItemPlus();
menuItem.Text = entry.GetShortDescription(28);
menuItem.Click += recentTasksMenuItem_Click;
menuItem.Tag = entry;
AddRecentMenuItem(menuItem);
}
}
private void AddRecentMenuItem(MenuItemPlus menuItem)
{
if (InvokeRequired)
{
BeginInvoke(new CallbackDelegate<MenuItemPlus>(AddRecentMenuItem), menuItem);
}
else
{
menuItemRecent.MenuItems.Add(menuItem); //<-- exception thrown here
}
}
delegate void CallbackDelegate<T>(T t);
有什么建议吗?
更新:我也尝试过调用 - 相同的结果。
menuItemRecent 是作为表单初始化例程的一部分创建的。线程在表单的激活事件上启动
I'm creating menu items in a separate thread and adding them to the menu created in the main thread. I'm using Invoke for that. Getting "Value does not fall within the expected range" exception.
//creating new thread
Thread thread = new Thread(LoadRecentTasks);
thread.IsBackground = true;
thread.Start();
private void LoadRecentTasks()
{
EntryCollection recentEntries = Entry.GetRecentEntries(10);
foreach (Entry entry in recentEntries)
{
MenuItemPlus menuItem = new MenuItemPlus();
menuItem.Text = entry.GetShortDescription(28);
menuItem.Click += recentTasksMenuItem_Click;
menuItem.Tag = entry;
AddRecentMenuItem(menuItem);
}
}
private void AddRecentMenuItem(MenuItemPlus menuItem)
{
if (InvokeRequired)
{
BeginInvoke(new CallbackDelegate<MenuItemPlus>(AddRecentMenuItem), menuItem);
}
else
{
menuItemRecent.MenuItems.Add(menuItem); //<-- exception thrown here
}
}
delegate void CallbackDelegate<T>(T t);
Any suggestions?
UPDATE: i've tried it with Invoke too - same result.
menuItemRecent is created as part of the form's initialization routine. The thread is started on form's Activated event
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设当控件未完全创建时会发生这种情况,导致 InvokeRequired 给您错误的读数。
I assume this happens when control is not fully created, causing InvokeRequired to give you a false reading.
嗯嗯。每当我调用 BeginInvoke 时,我总是这样做:
IIRC 正确,我总是使用对象数组,因为过去没有它我会遇到奇怪的异常。
Hmmmm. Whenever I call BeginInvoke I always do this instead:
IIRC correctly I always use the object array because without it in the past I've got weird exceptions.