ActiveX control cannot be instantiated because thread is in a single-threaded apartment. Happens after waking PC from sleep

madeFromCode picture madeFromCode · May 9, 2012 · Viewed 8.4k times · Source

I am working on a VOIP client (Window's form) that opens a browser window (ExtendedWebBrowser) when a call is made or received. Normally it works fine but if the computer is put into sleep mode and then woken the program will crash with the following error:

"System.Threading.ThreadStateException crossed a native/managed boundary
  Message=ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment."

I have tried setting threads started in the code with thread.SetApartmentState(ApartmentState.STA) but I am getting the same result. Also, I do have [STAThread] before the main() function. Now I am wondering if it has more to do with a thread not terminating correctly when the computer is put to sleep but I'm not sure. My background is in C++ and DirectX, this is the first Windows form I've worked on so any help would be appreciated.

Followup: I was able to resolve this issue after discovering that after resuming the program was being started on a worker thread instead of the main thread. More information can be read here: Sleep(suspend) and Resuming windows form starts program on worker thread instead of main thread

Answer

madeFromCode picture madeFromCode · May 17, 2012

I was able to resolve this issue. When the program resumed from sleep mode and run() was called it was being run on the windows event worker thread instead of the main thread. More information can be read here: Sleep(suspend) and Resuming windows form starts program on worker thread instead of main thread