Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to set the specified COM apartment state

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?

like image 473
Daniel Avatar asked Aug 02 '11 18:08

Daniel


1 Answers

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.

like image 116
Hans Passant Avatar answered Nov 02 '22 23:11

Hans Passant