开发者

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 STAThreadA开发者_StackOverflow社区ttribute 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜