I have a little problem with my WPF project and the FileSystemWatcher class. In my MainWindow class the watcher begins to watch a folder when Button Start is clicked in the UI. Everything works without any problems - the watcher recognizes correctly when a file is created. But while watcher is waiting it is not possible for user to do anything in the UI. It should be possible for nexample to click Stop...
private void Start_Click(object sender, RoutedEventArgs e)
{
rdbTextBox.Document.Blocks.Clear();
Start.IsEnabled = false;
rdbTextBox.Document.Blocks.Add(new Paragraph(new Run("Test gestarte-Warte auf Befund....")));
Stop.IsEnabled = true;
watcher = new FileSystemWatcher(ConfigSettings.Default.FilePath);
// Only watch text files.
// watcher.Filter = "*.bef";
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Created += OnCreated;
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait until new file in folder
watcher.WaitForChanged(System.IO.WatcherChangeTypes.Created);
watcher.Dispose();
// Parse letter
edifactLetter = parser.ParseDocument(ConfigSettings.Default.FilePath + "\\" + fileName);
// Validate Letter
edifactVal.Validate(edifactLetter);
writeResults();
Start.IsEnabled = true;
}
private void OnCreated(object sender, FileSystemEventArgs e)
{
FileInfo file = new FileInfo(e.FullPath);
fileName = file.Name;
}
Can anyone explain me what I am doing wrong? Thanks!
Yes, WaitForChanged
is a synchronous method:
This method waits indefinitely until the first change occurs and then returns.
You're calling that from the UI thread - therefore blocking any other UI thread interaction in the meantime. You don't want to do that.
You should probably just listen for the appropriate events - calling your parsing/validation methods in the event handler. You should also make sure you do all UI work in the UI thread, but ideally as little other work as possible... so unless the parsing and validation needs to interact with the UI, do it in a different thread.
See more on this question at Stackoverflow