Im having this excepton in the invoke mothod and i don't know why.
System.InvalidOperationException: 'Operación no válida a través de subprocesos: Se tuvo acceso al control 'Form2' desde un subproceso distinto a aquel en que lo creó.'
Google translate this as:
System.InvalidOperationException: 'Invalid operation through threads: The' Form2 'control was accessed from a different thread than the one in which it was created.'
If I call the invoke from a button for example it works correctly but I need to call this from the 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();
}