C# è nuovo per me e ho faticato con lo stesso problema per quasi una settimana. Ho avuto questa:
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;
}
}
Ho anche impostare l'intervallo del timer a 1 millisecondo e tuttavia alcuni nuovi eventi di file mancavano. Ho provato ad aggiornare notificationsListBox
dall'interno dell'evento onCreated
ma ho sempre ricevuto un errore di riferimento incrociato. Questo è stato fino a quando ho scoperto che l'evento onCreated
watcher è eseguito in un thread diverso da quello del thread del metodo principale, quindi, in una shell dado, questa è la mia soluzione:
Ho incluso public delegate void Action()
come un attributo del mio classe e quindi utilizzato Invoke
per aggiornare notificationsListBox
dall'interno dell'evento onCreated
. Successivamente, il codice pezzo:
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());}));
}
Quindi il timer e il relativo codice non sono più necessari. Questo funziona eccellente per me e spero lo faccia per chiunque abbia una situazione simile. Cordiali saluti !!!
Ricordare che FileSystemWatcher si basa sul sistema operativo per segnalare quando i file vengono aggiunti/modificati/eliminati/ecc. Quindi avere più istanze non aiuterà. –