Saturday, 5 September 2009

Why ApartmentState: [STA] needed at first place in WATiN?

While writing Automation code using WATiN we could observe that we need to mention ApartmentState as STA. In my initial period of time I was thinking why we need to mention STA?

On curiosity I tried to find out the reason behind it. I searched goggle, msdn and loads of blogs to get the exact cause behind it and at last I got the answer of it. Today I thought i should share my learning with others also.

STA: The Thread will create and enter a single-threaded apartment.

Let me put some point over here before moving into deep :)

1. Internet Explorer is not Thread safe we need to use STA.

2. And we are creating any instance of Internet Explorer through COM.

Now move into the deep inside ...

An apartment is a logical container within a process for objects sharing the same thread access requirements. All objects in the same apartment can receive calls from any thread in the apartment. The .NET Framework does not use apartments, and managed objects are responsible for using all shared resources in a thread-safe manner themselves.

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. You can control the type of apartment created by setting the ApartmentState property of the thread to one of the values of the ApartmentState enumeration. Because a given thread can only initialize a COM apartment once, you cannot change the apartment type after the first call to the unmanaged code.

Visit MSDN link for more Information.

Differences in ApartmentState between .Net 1.1 and .Net 2.0

I copied below explanation from MSDN.

In .Net 1.1 the default ApartmentState of a Thread is Unknown. A running Thread with this ApartmentState can be set to STA or MTA, but only once. Trying to set the Apartment state of a running Thread from MTA to STA (or vice versa) doesn’t have any effect, it remains MTA (or STA).

In .Net 2.0 the default ApartmentState of a Thread is MTA. Trying to reset the ApartmentState of a running Thread from MTA to STA (or vice versa) doesn’t have any effect, it remains MTA. Setting the ApartmentState to Unknown or STA instead of MTA, can ONLY be done BEFORE the Thread starts.

Happy WATiN Automation.

Please leave your comments.Thanks!!!

2 comments:

Anonymous said...

i without a doubt love your posting style, very charming.
don't quit as well as keep writing for the reason that it just simply worth to follow it.
looking forward to browse through a whole lot more of your own articles, have a pleasant day :)

Anonymous said...

Thanks for this simple explanation. Saved me a lot of time.