I'm creating new thread, in this thread i'm creating new menuItem that i want to add in menu on main window, but i'm getting errors like this (The calling thread cannot access this object because a different thread owns it).
Thread tempT = new Thread(new ThreadStart(LoadPlugins));
tempT.SetApartmentState(ApartmentState.STA);
tempT.IsBackground = true;
tempT.Start();
So in method "LoadPlugins" i'm creating new menuitem.
I tried to solve this error by:
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);
Nothing work, hope for help ;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);
}