WatiN and Thread.ApartmentState
This article explains why you need to set the Thread.Apartmentstate to STA when using WatiN. If you use a (test) runner which is not mentioned on this page but which needs some special setup to set the apartmentState to STA, please let me know so I can add the info to this page.
Index
- Why is setting the ApartmentState needed in the first place?
- Differences in ApartmentState between .Net 1.1 and .Net 2.0.
- Implications.
- Behaviour of WatiN when Thread is not an STA Thread.
- Using WatiN in a console or WinForms application.
- Using WatiN and MBUnit.
- Using WatiN and NUnit.
- Using WatiN and MSTest.
- Using WatiN and TestDriven.Net in VS 2003 and VS2005.
- Using WatiN and SharpDevelop’s NUnit test runner.
- Using WatiN and Fitnesse.
Why is setting the ApartmentState needed in the first place?
Copied from MSDN:
“Because COM classes use apartments, the common language runtime needs to create and initialize an apartment when calling a COM object in a COM interop situation. A managed thread can create and enter a single-threaded apartment (STA) that allows only one thread, or a multithreaded apartment (MTA) that contains one or more threads.”.
Since Internet Explorer is not Thread safe we need to use STA.
Implications
Using WatiN works fine in a console or GUI application when you apply the [STAThread] attribute to the main method (the sole entry point of the application). This way the main Thread runs as STA and all goes well. When using a runner like MBUnit, NUnit or any other runner that starts the main Thread, your code/tests depend upon the ApartmentState the runner started with.
Behaviour of WatiN when Thread is not an STA Thread.
WatiN will throw a ThreadStateException when you create an instance of the WatiN.Core.IE class, to help you remind to set the ApartmentState to STA.

