Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I set a thread to ApartmentState.STA? [closed]

Tags:

c#

.net

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(); 
} 
like image 712
Unknown Avatar asked Oct 22 '25 23:10

Unknown


2 Answers

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

like image 101
Joe Avatar answered Oct 25 '25 18:10

Joe


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.

like image 28
Aineislis Cole Avatar answered Oct 25 '25 20:10

Aineislis Cole