Failed to set the specified COM apartment state

99封情书 提交于 2019-12-07 09:23:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6917134/failed-to-set-the-specified-com-apartment-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!