5

It seems that I really am not good with multithreaded applications. I am trying to open a FolderBrowserDialog, but I was getting an exception telling me:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made.

I have STAThreadAttribute set in my Main method, but the FolderBrowserDialog is being called from a thread other than my main thread. I tried

Thread.CurrentThread.SetApartmentState(ApartmentState.STA);

but that gave the exception Failed to set the specified COM apartment state.

I have a temporary fix that creates a new thread in STA mode and opens the FolderBrowserDialog, but I would like to have a neater solution. What causes a failure to set the apartment state to STA?

Daniel
  • 6,595
  • 9
  • 38
  • 70
  • 1
    Better to set `Threading.ApartmentState.STA` when you creating any thread which access OLE related functions. – Damith Aug 02 '11 at 19:20

1 Answers1

14

You have to call SetApartmentState() before you start the thread. COM is initialized by the CLR before any the thread starts running any managed code. Also note that you cannot do this on threadpool threads, including BackgroundWorker's.

Using windows on more than one thread is in general a bad idea. The windows on the thread have no Z-order relationship to the windows on the main UI thread. This can cause very awkward usability problems. Like this dialog hiding behind the main window. No taskbar button either, the user will never find it.

Don't do this, use Control.Invoke() so the dialog is modal to the other windows. Or more in general, use worker threads only for non-UI tasks.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Wait a minute, how can you set the state of the current state before it's started? Doesn't `Thread.CurrentThread.SetApartmentState(...)` imply that the thread is already running? – kristianp Mar 12 '17 at 23:37
  • 1
    It is nonsense code, that's why he got the exception. SetApartmentState() must strictly be called *before* calling Start(). – Hans Passant Mar 12 '17 at 23:44