I'm writing a console application that scans a directory for files and uploads the data in them to a database. The files are a proprietary type that require a specific library that requires the program to be run on an STA thread. When I call my function to upload the files in an OnCreated FileSystemWatcher method, I get an error warning about needing to run in an STA Thread. This doesn't show up when I call the upload function directly in the Main() function using a direct file path.
I've done a bit of research into this and found that the FileSystemWatcher calls its events in a separate thread. It seems if you are using Winforms or WPF you can set the SynchronizingObject property to your UI element, and it will run on the main UI thread. I couldn't find any information on how this would apply to a console application, however. So basically I'm wondering if there's any way to get FileSystemWatcher to run on the main thread, or to make the secondary thread it runs the functions I've made in, run as an STA thread.
Here is a solution based on a TaskScheduler, not related to Winforms nor WPF. It allows you to use all Task-related functions and tooling: