【发布时间】:2019-11-13 15:18:45
【问题描述】:
我在调用方法中有这个异常,我不知道为什么。
System.InvalidOperationException: 'Operación no válida a traves de subprocesos: Set tuvo acceso al control 'Form2' desde un subproceso distinto aquel en que lo creó。'
谷歌将其翻译为:
System.InvalidOperationException: '通过线程的无效操作:'Form2'控件是从与创建它的线程不同的线程访问的。'
例如,如果我从按钮调用调用它可以正常工作,但我需要从 FileSystemWatcher 调用它。
List<Thread> listThreads = new List<Thread>();
private void Form1_Load(object sender, EventArgs e)
{
RunFileSystemWatcher();
}
public void RunFileSystemWatcher()
{
FileSystemWatcher fsw = new FileSystemWatcher();
fsw.Path = "C:/Users/Gaming/Documents";
fsw.NotifyFilter = NotifyFilters.LastAccess;
fsw.NotifyFilter = NotifyFilters.LastWrite;
//fsw.NotifyFilter = NotifyFilters.Size;
//fsw.Created += FileSystemWatcher_Created;
fsw.Changed += FileSystemWatcher_Changed;
fsw.Filter = "*.txt";
fsw.EnableRaisingEvents = true;
}
Boolean abrir = true;
private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
if (abrir) {
for (int i=0; i<5; i++)
{
Thread hilo = new Thread(() => showForms(new Form2()));
hilo.Start();
listThreads.Add(hilo);
abrir = false;
}
}
else{
for(int i=0; i<listThreads.Count; i++)
{
try
{
Invoke((MethodInvoker)delegate {
listForms[i].Close();
});
listThreads[i].Abort();
}
catch (ThreadAbortException)
{
}
}
}
}
List<Form2> listForms = new List<Form2>();
private void showForms(Form2 form)
{
listForms.Add(form);
form.ShowDialog();
}
【问题讨论】: