Friday, December 7, 2007

Threading Principles

Multiple Threads in Applications

If you programmed in versions of VB prior to .NET, you might know that VB supported multiple threads within a COM container, such as MTS or COM+. Well, although multiple threads were supported by VB5/6, the threading model they supported was Single Threaded Apartments (STA). If you come from Visual C++ then you'd have options to build both MTA (Multi Threaded Apartments) and STA applications. However, the .NET Framework does not retain the concept of Apartments and it manages all of the threads within AppDomains. By default, all .NET applications are multithreaded and any code can access any object at any time. Thus, we have to be very careful with static resources in the managed code.

The .NET Framework supports both managed and unmanaged threads and all the Win32 threading models such as STA and MTA. When you are trying to access COM components from managed code, unmanaged threads are created by the legacy COM components. Threads in the .NET Framework are created using the Thread object, whether managed or unmanaged.

If you have ever programmed multithreaded programs using the Win32 APIs, you may remember that Win32 supported user-interface threads and worker threads. the threading names have now changed into Apartment Model Threading and Free Threading respectively. The .NET Framework supports two basic threading models, which are Apartment Model Threaded or Single Threaded Apartment (STA) components, and Free Threaded or Multi Threaded Apartment (MTA) components. When we create a thread in .NET, by default it is an MTA thread.

No comments: