0

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();

    }
juanpalomo
  • 63
  • 1
  • 8
  • Possible duplicate of [How to access a WinForms control from another thread i.e. synchronize with the GUI thread?](https://stackoverflow.com/questions/58657831/how-to-access-a-winforms-control-from-another-thread-i-e-synchronize-with-the-g) –  Nov 13 '19 at 07:20

1 Answers1

1

You have a synchronize with the main thread UI conflict.

You must sync the call to any action on UI controls with the main thread.

You can use a BackgroundWorker.

Or this:

static public class SyncUIHelper
{
  static public Thread MainThread { get; private set; }

  // Must be called from the Program.Main or the Main Form constructor for example
  static public void Initialize()
  {
    MainThread = Thread.CurrentThread;
  }

  static public void SyncUI(this Control control, Action action, bool wait = true)
  {
    if ( !Thread.CurrentThread.IsAlive ) throw new ThreadStateException();
    Exception exception = null;
    Semaphore semaphore = null;
    Action processAction = () =>
    {
      try { action(); }
      catch ( Exception except ) { exception = except; }
    };
    Action processActionWait = () =>
    {
      processAction();
      if ( semaphore != null ) semaphore.Release();
    };
    if ( control != null
      && control.InvokeRequired
      && Thread.CurrentThread != MainThread )
    {
      if ( wait ) semaphore = new Semaphore(0, 1);
      control.BeginInvoke(wait ? processActionWait : processAction);
      if ( semaphore != null ) semaphore.WaitOne();
    }
    else
      processAction();
    if ( exception != null ) throw exception;
  }

}

Usage:

this.SyncUI(listForms[i].Close /*, true or false to wait or not */);

And:

this.SyncUI(() => form.ShowDialog() /*, true or false to wait or not */);

With:

private void Form1_Load(object sender, EventArgs e)
{
  SyncUIHelper.Initialize();
  RunFileSystemWatcher();
}

You need to correct your code in FileSystemWatcher_Changed because it is buggy.