首页 > 解决方案 > 检查文件系统内的控制更改 Watcher Changed 事件导致异常

问题描述

我有一个FileSystemWatcher_Changed事件,我想检查表单上任何控件的状态是否已更改。然后我想更新一个发生变化的 json 文件。

问题是当我尝试使用已更改事件中的调度程序检查更改时,我得到一个异常:

对象同步方法是从未同步的代码块中调用的。

我提到了这篇文章,但无法提取任何与我的案件有关的信息。来自未同步块的对象同步方法。

private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            try
            {
                //Deserialize, check length, if len >1 then check both are inactive and if both are inactive then only lock
                //var root = JsonConvert.DeserializeObject<Root>(wc.GetFullJsonText());
                var root = JsonConvert.DeserializeObject<Root>(wc.GetFullJsonText());
                if (root != null && root.AllApplications != null)
                {
                    var item = root.AllApplications.Any(x => x.Status == ActivityStatus.Active.ToString());
                    if (!item)
                    {
                        if (InActivecount == 0)
                        {
                            Program.IdleTimer.Tag = InActivityTimer.Ended;
                            //MessageBox.Show("I am hiding because Main App is InActive");
                            this.Invoke((MethodInvoker)delegate //I think this is causing an issue.
                            {
                                CheckChanged();
                            });
                            this.Hide();
                        }
                        InActivecount++;
                    }
                    else
                    {
                        if ((InActivityTimer)Program.IdleTimer.Tag == InActivityTimer.Ended)
                        {
                            this.Show();
                            UnRegister(sender as FileSystemWatcher);
                            UpdateActivityStatus();
                            Program.StartInActivityMonitor();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.InnerException.ToString());
            }
        }


private void CheckChanged()
        {
            foreach(var item in this.Controls)
            {
                if(item is TextBox)
                {
                    control = item;
                    (control as TextBox).TextChanged += Form1_TextChanged;
                }
            }
        }

        private void Form1_TextChanged(object sender, EventArgs e)
        {
            wc.AddStatusToGeneStudy(true);
            (control as TextBox).TextChanged -= Form1_TextChanged;
        }

标签: c#winformsfilesystemwatcher

解决方案


推荐阅读