STAThread和MTAThread中是C#中的常见的两种模式,其中STAThread: single threaded apartment 直译过来是:单线程单元套间; MTAThread:multiple threaded apartment 直译过来是:多线程单元套间。
其他线程对STA中的COM对象的访问需要列集(marshal),通过列集,自动实现了多线程访问下的同步。所有线程对MTA中的COM对象的访问不需要列集,直接访问,需要COM组件自身实现多线程下的同步。
在编写Window Form 程序时会遇到使用COM对象的场景,这个时候可以使用以下两种方式指定MTAThread模式。代码如下:
Program类如下:
static class Program
{
static System.Threading.Thread _thread;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
_thread = new System.Threading.Thread(HostProcess);
_thread.IsBackground = true;
_thread.Start();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
[MTAThread]
static void HostProcess()
{
ControlService.StartService();
}
}
除此之外我也还可以指定Thread的模式如下:
System.Threading.Thread _thread;
_thread = new System.Threading.Thread(MyFun);
_thread.IsBackground = true;
_thread.SetApartmentState(System.Threading.ApartmentState.MTA);
_thread.Start();
两种方式效果都是一样的。