Brett said:
C# code automatically generates [STAThread] or [MTAThread] references.
Single or Multi apartment threads. What exacty does this do and what
will happen if I remove it?
Is MTAThread necessary if I want to use multiple threads in my app?
Also, why doesn't VB use STA or MTA thread?
Thanks,
Brett
VS for VB.NET doesn't set this attribute on the main entry, but the
compiler generates the code that initializes the thread for STA (Single
Threaded Apartments) by default.
C# sets this attribute to [STAThread] because it's required in Windows
Forms applications, other type of applications need to set it explicitly
depending on the COM requirements.
Now why is it required to set the attribute in C#?
It tells the compiler to emit the code to initialize the thread for COM
interop. Windows Forms needs it for two reasons:
1. Cut and paste support, which is an OLE technology that requires a STA.
2 COM interop with ActiveX controls (directly or indirectly) used as UI
elements.
AX COM objects are all STA type COM objects they need to run on a STA
thread and they can only be called directly from this same thread, calls
from other threads are automatically marshaled, which implies overhead and
serialized (only one call at a time).
MTA (Multi Threaded Apartment) type of COM objects (also called free
threaded) need a MTA initialized thread to run on but can be called from
any thread (simultaneously) without incurring a marshaling overhead.
So, you definitely need the STAThread attribute for Windows applications.
Most console applications can safely use STAThread, but you better set the
MTAThread attribute if you need to call into "free threaded" COM objects
from your main thread. COM object marked as threading model "both" can run
on both STA and MTA, but its better to run them on STA threads.
Windows Services don't host ActiveX objects (they shouldn't) so here there
is no need (and you can't) to set this attribute. If you need to call into
COM from a Service you have to initialize the thread by setting the
AppartmentState property of the thread in your code.
Willy.