Programming Microsoft Windows with C#
ThreadStateException Raised in Some Programs
Some programs — particularly those towards the end of the book and
in Chapter 24 — may prematurely terminate with the message:
System.Threading.ThreadStateException: The current thread must set to Single Thread Apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.
To fix the problem, insert the statement:
System.Threading.Thread.CurrentThread.ApartmentState = System.Threading.ApartmentState.STA;
in Main right before the Application.Run statement.
You may notice some other programs in the book
(NotepadClone, NotepadCloneWithPrinting, and TextBoxWithToolBar)
already contain this statement.
It's also possible to fix the problem by inserting the line:
right before the definition of Main.
© Charles Petzold, 2002
This page last updated March, 2002