Failed to set the specified COM apartment state
Asked Answered
T

1

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?

Teillo answered 2/8, 2011 at 18:58 Comment(1)
Better to set Threading.ApartmentState.STA when you creating any thread which access OLE related functions.Trophoplasm
W
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.

Wiese answered 2/8, 2011 at 21:18 Comment(2)
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?Sikes
It is nonsense code, that's why he got the exception. SetApartmentState() must strictly be called before calling Start().Wiese

© 2022 - 2024 — McMap. All rights reserved.