Search code examples
c#multithreadingworker-thread

Is it not possible to show a FolderBrowserDialog from a non-UI thread?


I'm facing problem in showing FolderBrowserDialog instance created and called from a non-UI thread. It doesn't get renders properly.

Being more specific, it doesn't shows the folder tree but displays only the Make New Folder OK and Cancel

alt text


Solution

  • All the shell dialogs, including FolderBrowserDialog, require the COM apartment for the thread to be set to STA. You are probably missing the Thread.SetApartmentState() call:

        private void button1_Click(object sender, EventArgs e) {
            var t = new Thread(() => new FolderBrowserDialog().ShowDialog());
            t.IsBackground = true;
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        }
    

    Beware that you cannot set the owner of the dialog, it easily gets lost behind a window of another application. Which makes showing forms or dialogs on a worker thread less than a good idea.