I have a FileSystemWatcher_Changed
event where I want to check if the state of any of the controls on the form has changed. Then I want to update a json file that something changed.
Problem is when I try to check the change using a Dispatcher inside the changed event I get an exception:
Object synchronization method was called from an unsynchronized block of code.
I referred to this post but couldn't pull any info relating my case. Object synchronization method from unsynchronized block.
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;
}