.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.
If you're new and want to update, check See here how to update to NET Core 3.0

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.
  1. using System.IO;
  2. using System.Windows.Forms;
  3. namespace FileSystemWatcherSampleNETCore3._0
  4. {
  5. public partial class Form1 : Form
  6. {
  7. public Form1()
  8. {
  9. InitializeComponent();
  10. var fw = new FileSystemWatcher
  11. {
  12. Filter = "*.pdf",
  13. Path = "C:\\Users\\..\\Local", // Any path
  14. IncludeSubdirectories = false,
  15. SynchronizingObject = this,
  16. EnableRaisingEvents = true
  17. };
  18. // On .NET Core 3.0 MonikerChange runs in a different Thread
  19. fw.Changed += MonikerChange;
  20. // On .NET Framework 4.x, 3.x etc. It runs in the same Thread
  21. }
  22. /// <summary>
  23. /// The delegate is used to make the connection between Threads
  24. /// </summary>
  25. /// <param name="e"></param>
  26. private delegate void UpdateUIWatcherDelegate(FileSystemEventArgs e);
  27. /// <summary>
  28. /// Event Fired in the second thread
  29. /// </summary>
  30. /// <param name="sender"></param>
  31. /// <param name="e"></param>
  32. private void MonikerChange(object sender, FileSystemEventArgs e) => UpdateUIWatcher(e);
  33. /// <summary>
  34. /// Invoke to the new Thread
  35. /// </summary>
  36. /// <param name="e"></param>
  37. private void UpdateUIWatcher(FileSystemEventArgs e) =>
  38. _ = Invoke(new UpdateUIWatcherDelegate(MonikerChangeUIThread), e);
  39. /// <summary>
  40. /// Now you can update
  41. /// Directly the UI in the Form on any other UI on the WinForms App
  42. /// </summary>
  43. /// <param name="e"></param>
  44. private void MonikerChangeUIThread(FileSystemEventArgs e)
  45. {
  46. // LoadPDF(e.FullPath); // Load the UI
  47. }
  48. }
  49. }
I've added the sample code with this post.
I hope this could help the community and speed up your development.
Happy coding!