FolderBrowseDialog STAThread error in background worker
-
28-04-2021 - |
Question
Good day,
I'm getting an error very similar to the one discussed here (among other sources here and elsewhere): STAThread missing, but it is there
The difference is that in my case I am using multi-threading. A BackgroundWorker
is generating documents and when it's done, a FolderBrowseDialog
will pop up to allow the user to choose a location to save the generated documents. So I can understand why I'm receiving this error. The reason I chose to put the FolderBrowseDialog
in the BackgroundWorker
events and related code is because then I have direct access to the path in stead of passing the string from one thread to the other.
Funny thing though, PrintDialog
works but SaveFileDialog
and FolderBrowseDialog
throws this error.
I would just like to hear your thoughts. Would it be best to move the FolderBrowseDialog
out of the BackgroundWorker
code? Should I implement a custom FolderBrowseDialog
? Is there any way around this?
Thanks in advance for comments and advice and to everyone taking the time to consider my question; much appreciated.
Kind regards
Solution
Is the FolderBrowseDialog being called in the RunWorkerCompleted callback or is it being called in the DoWork callback? If you're calling it from the DoWork callback, you'll need to use the SynchronizationContext the BackgroundWorker was created in and use the Send method to show the FolderBrowseDialog.
http://thedersen.com/2010/05/23/showing-modal-dialogs-from-a-background-thread/ is the closest example I can find on the web. In that example, the Worker class is used to store the SynchronizationContext.