我遇到以下问题:我有一个配置文件和一个监听器。更改后,触发修改createMenuAndItems
的方法(toolStripMenuItem
)。
在加载Form时以及修改配置文件时调用方法createMenuAndItems
。每当数组
strArrays = new string[] { "Copy File" , "Exit"};
有多个项目,在修改配置文件时显示错误。加载表格工作正常。
Visual Studio中显示的错误:
System.InvalidOperationException未处理
的HResult = -2146233079
Message =:跨线程操作无效:控制'topMenu'从其创建的线程以外的线程访问
实际消息是
Message =Operaciónnoválidaratravésdesubprocesos:Se tuvo acceso al control'topMenu'desde un subproceso distinguished to a aquel en quelocreó。
源= System.Windows.Forms的
堆栈跟踪:
尝试CheckForIllegalCrossThreadCalls = False;
但没有运气
奇怪的是,如果数组strArrays
只有一个值,它就像一个魅力。但是当添加更多项目时开始显示此错误
这是代码。
文件上的监听器:
private void configWatcher()
{
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher()
{
Path = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\\Launcher"),
Filter = "Config.xml"
};
fileSystemWatcher.Changed += new FileSystemEventHandler(this.createMenuAndItems);
fileSystemWatcher.EnableRaisingEvents = true;
}
以下是创建和修改toolStripMenuItem
private void createMenuAndItems()
{
string str;
ToolStripMenuItem toolStripMenuItem;
int i;
base.Invoke(new Action(() =>
{
base.Controls.Find("topMenu", false);
if (base.Controls.IndexOfKey("topMenu") > 0)
{
base.Controls.RemoveByKey("topMenu");
}
}));
MenuStrip menuStrip = new MenuStrip()
{
Name = "topMenu"
};
base.Invoke(new Action(() => this.Controls.Add(menuStrip)));
string[] strArrays = new string[] { "Menú" };
string[] array = strArrays;
for (i = 0; i < (int)array.Length; i++)
{
ToolStripMenuItem toolStripMenuItem1 = new ToolStripMenuItem(array[i]);
menuStrip.Items.Add(toolStripMenuItem1);
}
foreach (ToolStripMenuItem item in menuStrip.Items)
{
if (item.Text == "Menú")
{
strArrays = new string[] { "Copy File" , "Exit"};
array = strArrays;
for (i = 0; i < (int)array.Length; i++)
{
str = array[i];
toolStripMenuItem = new ToolStripMenuItem(str, null, new EventHandler(this.ChildClick));
item.DropDownItems.Add(toolStripMenuItem);
}
foreach (ToolStripMenuItem dropDownItem in item.DropDownItems)
{
if (dropDownItem.Text == "Copy File")
{
//gives a list of strings.
array = this.fetchServersFromConfig().ToArray();
for (i = 0; i < (int)array.Length; i++)
{
str = array[i];
toolStripMenuItem = new ToolStripMenuItem(string.Concat("Origin: ", str), null, new EventHandler(this.copyFile));
dropDownItem.DropDownItems.Add(toolStripMenuItem);
}
}
if (dropDownItem.Text == "Exit")
{
dropDownItem.ShortcutKeys = Keys.Control | Keys.Q;
dropDownItem.Click += new EventHandler(this.exitButtonMenu);
}
}
}
}
}
谢谢!
答案 0 :(得分:1)
最后通过configWatcher()
像这样:
fileSystemWatcher.Changed += new FileSystemEventHandler(base.Invoke(new Action(() => this.createMenuAndItems())););
而不是:
fileSystemWatcher.Changed += new FileSystemEventHandler(this.createMenuAndItems);