STA mode Error

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
 
K

Ken Slovak - [MVP - Outlook]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top