.NET Core 3.0
.NET Core 3.0 is the new incarnation for .NET Framework with upgrades, launched on 9/23/2019. .NET Core 3.0 has compatibility with several distros of Linux and runs on macOS too. .NET Core 3.0 has support for WinForms and WPF, but you will not be able to run it on Linux and macOS.
I'm writing this blog because when I updated to NET Core 3.0, the app it was just quit while running and I found the reason and hence this post.
FileSystemWatcher in .NET Framework
In .NET Framework 4.x, 3.x, etc. the objects run in the same thread of the UI and events fired can change the UI directly. This can cause slow the UI.
FileSystemWatcher in .NET 3.0
Great update of FileSystemWatcher comes in NET Core 3.0 and now it runs in a separate thread so the main UI is not affected with any delays. However, it cannot update UI directly via events. More information about FileSystemWatcher you can get on
Microsoft Documentation.
Masterstroke
To implement the change is needed to use delegates, which communicate between threads.
Follow in the code below how to implement it.
- using System.IO;
- using System.Windows.Forms;
-
- namespace FileSystemWatcherSampleNETCore3._0
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
-
- var fw = new FileSystemWatcher
- {
- Filter = "*.pdf",
- Path = "C:\\Users\\..\\Local",
- IncludeSubdirectories = false,
- SynchronizingObject = this,
- EnableRaisingEvents = true
- };
-
-
-
- fw.Changed += MonikerChange;
-
-
-
- }
-
-
-
-
-
-
- private delegate void UpdateUIWatcherDelegate(FileSystemEventArgs e);
-
-
-
-
-
-
- private void MonikerChange(object sender, FileSystemEventArgs e) => UpdateUIWatcher(e);
-
-
-
-
-
- private void UpdateUIWatcher(FileSystemEventArgs e) =>
- _ = Invoke(new UpdateUIWatcherDelegate(MonikerChangeUIThread), e);
-
-
-
-
-
-
- private void MonikerChangeUIThread(FileSystemEventArgs e)
- {
-
- }
-
-
- }
- }
I've added the sample code with this post.
I hope this could help the community and speed up your development.
Happy coding!