我正在创建新线程,在这个线程中我创建了我想要在主窗口的菜单中添加的新menuItem,但是我得到这样的错误(调用线程无法访问这个对象,因为一个不同的线程拥有它)。
Thread tempT = new Thread(new ThreadStart(LoadPlugins));
tempT.SetApartmentState(ApartmentState.STA);
tempT.IsBackground = true;
tempT.Start();
所以在方法" LoadPlugins"我正在创建新的menuitem。
我试图通过以下方式解决此错误:
Main_Menu.Dispatcher.Invoke(new Action(() => { Main_Menu.Items.Add(Plugin_Menu); }), System.Windows.Threading.DispatcherPriority.ContextIdle);
Dispatcher.BeginInvoke(new Action(() => { Main_Menu.Items.Add(Plugin_Menu); }), System.Windows.Threading.DispatcherPriority.ContextIdle);
没什么可行的,希望得到帮助; D
private void LoadPlugins()
{
MenuItem Plugin_Menu = new MenuItem();
Plugin_Menu.Header = "Plugins";
Plugin_Menu.Template = (ControlTemplate)FindResource("twMenuItem");
plugins.Clear();
DirectoryInfo pluginDirectory = new DirectoryInfo(pluginPath);
if (!pluginDirectory.Exists)
{
pluginDirectory.Create();
}
var pluginFiles = Directory.GetFiles(pluginPath, "*.dll");
foreach (var file in pluginFiles)
{
Assembly asm = Assembly.LoadFrom(file);
var types = asm.GetTypes().
Where(t => t.GetInterfaces().
Where(i => i.FullName == typeof(IPlugin).FullName).Any());
foreach (var type in types)
{
var plugin = asm.CreateInstance(type.FullName) as IPlugin;
plugins.Add(plugin);
}
}
foreach(IPlugin plugin in plugins)
{
MenuItem tempMenuItem = new MenuItem();
tempMenuItem.Header = plugin.name;
tempMenuItem.Template = (ControlTemplate)FindResource("twMenuItem");
tempMenuItem.Click += (sender, args) =>
{
plugin.Init();
};
Plugin_Menu.Items.Add(tempMenuItem);
}
Dispatcher.BeginInvoke(new Action(() => { Main_Menu.Items.Add(Plugin_Menu); }), System.Windows.Threading.DispatcherPriority.ContextIdle);
}