4

I am curious to know when STA/MTA are used in C# .net?

using (ManualResetEventSlim mre = new ManualResetEventSlim(false)) 
{       
    Thread _STAThread = new Thread(new ThreadStart(() =>                 
        {
             globalComObject = new ComClass();                     
             mre.Set();                     
             try                     
             {                         
                  Thread.CurrentThread.Join();
             }
             catch (ThreadAbortException)                     
             { } 
         }));
     _STAThread.SetApartmentState(ApartmentState.STA);                    
     _STAThread.IsBackground = true;                 
     _STAThread.Start();                 
     mre.Wait(); 
} 
Sam Saffron
  • 124,587
  • 78
  • 320
  • 501
Unknown
  • 304
  • 1
  • 3
  • 15

2 Answers2

5

You use them when doing interop with STA/MTA COM objects.

Joe
  • 118,426
  • 28
  • 194
  • 329
5

This stackoverflow answer would give you a plenty. Read also this and this MSDN page. The gist of it is that STA apartment is used for non thread-safe COM objects, while MTA can be used thread-safe COM objects in a multi-threaded fashion.

Community
  • 1
  • 1