C# is new to me and I struggled with the same trouble for nearly a week. I had this:
private void btnWatchFile_Click(object sender, EventArgs e)
{
//code to create a watcher and allow it to reise events...
}
//watcher onCreate event
public void onCreated(object sender, FileSystemEventArgs e)
{
if (!updateNotifications )
{
stringBuilder.Remove(0, stringBuilder.Length);
stringBuilder.Append(e.FullPath);
stringBuilder.Append(" ");
stringBuilder.Append(e.ChangeType.ToString());
stringBuilder.Append(" ");
stringBuilder.Append(DateTime.Now.ToString());
updateNotifications = true;
}
}
//timer to check the flag every X time
private void timer_Tick(object sender, EventArgs e)
{
if (updateNotifications )
{
notificationListBox.Items.Insert(0, stringBuilder.ToString());
updateNotifications = false;
}
}
I even set the timer interval to 1 millisecond and yet some new file events were missing. I tried to update the notificationsListBox
from inside the onCreated
event but I always got a Cross-reference error. This was until I found out that the watcher onCreated
event is executed in a thread other than the one of the main method thread, so, in a nut shell, this is my solution:
I included public delegate void Action()
as an attribute of my class and then used Invoke
to update the notificationsListBox
from inside the onCreated
event. Next, the piece code:
public void onCreated(object sender, FileSystemEventArgs e)
{
stringBuilder.Remove(0, stringBuilder.Length);
stringBuilder.Append(e.FullPath);
stringBuilder.Append(" ");
stringBuilder.Append(e.ChangeType.ToString());
stringBuilder.Append(" ");
stringBuilder.Append(DateTime.Now.ToString());
updateNotifications = true;
Invoke((Action)(() => {notificationListBox.Items.Insert(0, stringBuilder.ToString());}));
}
So the timer and its code are no longer necessary.
This works excellent for me and I hope it does for anyone with a similar situation.
Best regards!!!