STA mode Error

  • Thread starter Thread starter Matt
  • Start date Start date
M

Matt

Hello,

I wasn't getting this error until I threw my code, which initiated/called my
Form to load, into a try/catch statement.

"Current thread must be set to single thread apartment (STA) mode before OLE
calls can be made. Ensure that your Main function has STAThreadAttribute
marked on it."

I don't have a Main function in my code for my COM add-in for Outlook, so
how would I go about fixing this error so that I can load my Form.

Thanks
 
That error usually occurs in relation to WordMail objects in Outlook 2003 or
earlier. In that case WordMail is not running in the same process space as
Outlook is and the threading is different. It also can happen from
background threads (which never, ever should be used to access the Outlook
object model).

Your Connect class is running in process with Outlook and in the same
thread. You would need to set up a callback into the main thread. I usually
get the current thread context in Connect, at NewInspector() and
NewExplorer(). Often to prime the message pump I call
System.Windows.Forms.Application.DoEvents() before I get the context so it
isn't null.

I then store that context and put any thread sensitive code in Connect so it
runs in the main thread. When I need to synch to that thread I use a
System.Threading.SendOrPostCallback utilizing the persisted main thread
context.
 
Back
Top