System.InvalidOperationException调用异常

时间:2019-09-26 20:06:00

标签: c# exception invoke

我在调用方法中有这个除外,我不知道为什么。

  

System.InvalidOperationException:'子过程的操作:安全控件'Form2'决定了子过程是否与aquel en cre lo分开。'

Google将其翻译为:

  

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

    }

1 个答案:

答案 0 :(得分:1)

您有与主线程UI同步的冲突。

您必须使用主线程将调用同步到UI控件上的任何操作。

您可以使用BackgroundWorker。

或者这个:

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;
  }

}

用法:

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

并且:

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

使用:

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

您需要在FileSystemWatcher_Changed中更正代码,因为它有错误。