When using single-threaded apartment (STA) COM components, such as
components developed using Visual Basic, from an ASP.NET page, you
must include the compatibility attribute AspCompat=true in an
<%@ Page>
tag on the ASP.NET page
The AspCompat attribute forces the page to execute in STA mode
ASP.NET by default uses MTA (multi-threaded apartment) threads
When building ASP.NET applications that interface with old school COM
objects like those created with VB6 or Visual FoxPro (MTDLL), it's
extremely important that the threads that are serving requests use
Single Threaded Apartment Threading. STA is a COM built-in technology
that allows essentially single threaded components to operate reliably
in a multi-threaded environment. STA's guarantee that COM objects
instantiated on a specific thread stay on that specific thread and any
access to a COM object from another thread automatically marshals that
thread to the STA thread. The end effect is that you can have multiple
threads, but a COM object instance lives on a fixed never changing
thread.
ASP.NET by default uses MTA (multi-threaded apartment) threads which
are truly free spinning threads that pay no heed to COM object
marshaling. This is vastly more efficient than STA threading which has
a bit of overhead in determining whether it's OK to run code on a
given thread or whether some sort of thread/COM marshaling needs to
occur. MTA COM components can be very efficient, but STA COM
components in a multi-threaded environment always tend to have a fair
amount of overhead.
STA in ASP.NET
Support for STA threading in the ASP.NET framework is fairly limited.
Specifically only the original ASP.NET WebForms technology supports
STA threading directly via its STA Page Handler implementation or what
you might know as ASPCOMPAT mode. For WebForms running STA components
is as easy as specifying the ASPCOMPAT attribute in the @Page tag:
<%@ Page Language="C#" AspCompat="true" %>
which runs the page in STA mode. Removing it runs in MTA mode. Simple.
STA for non supporting ASP.NET Technologies
only WebForms supports STA natively
- ASP.NET HttpHandlers
- ASMX Web Services
- ASP.NET MVC
- WCF Web Services
- ASP.NET Web API
STA components are a pain in the ass. I feel your pain :-)
Good reference:
https://weblog.west-wind.com/posts/2012/Sep/18/Creating-STA-COM-compatible-ASPNET-Applications#STAfornonsupportingASP.NETTechnologies