人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

September 15, 2006

STAThreadAttribute

Filed under: .NET

在VS中,生成一个windows application,程序的Main()函数上会应用
STAThreadAttribut, 而生成Console application就不会应用这个Attribute

static class Program
{
[STAThread]
static void Main()
{

Application.Run(new Form1());
}
}

class Program
{
static void Main(string[] args)
{
}
}

缺省情况下,application的主线程的Apartment state为multi-threaded apartment
(ApartmentState.MTA),设置主线程Apartment state的唯一方法就是使用STAThreadAttribut.

STAThreadAttribut使得一个application的COM 线程模式为single-threaded apartment (STA),
STAThreadAttribut只能应用在程序的入口函数上,对于其他的函数不起作用,

在程序中设置一个线程的COM 线程模式,也可以使用如下的代码:

Thread t = new Thread(new ThreadStart(StartNewStaThread));
//.net1.1
t.ApartmentState = ApartmentState.STA;
t.Start();

private void StartNewStaThread()
{
Application.Run(new Form1());
}
在.net2.0中Thread.ApartmentState被Thread.SetApartmentState (ApartmentState state)取代

注意线程的Apartment state 必须要在线程启动前设置.

从逻辑上说,apartment 是线程和object的容器,apartment中的object可以被这个apartment中任何
一个线程访问. 一个STA只能包含一个线程,一个MTA可以包含多个线程。MTA中各线程可以并行的调用
本公寓内实例化的组件一个进程可以包含多个STA,但只能有一个MTA。

.NET framework不使用apartment 模式, 所有的managed object在使用共享资源时自发地保证线程
安全.由于COM使用了apartment,所以CLR在操作COM ojbect时需要生成和初始化apartment.常用的COM组件有
Clipboar和File Dialog.COM 线程模型只适用于使用 COM interop 的应用程序。如果将此属性应用到
不使用 COM interop 的应用程序,将没有任何效果。
Windows Forms不支持MTA.所以windows程序要使用STAThreadAttribut

在Fantasy Soft的bolg不可错过的MSDN TV-IronPython: Python on the .NET Framework,有
下列描述:
如果你打算在Interactive Mode下面直接执行以上代码,你会碰到如下的错误:
Traceback (most recent call last):
at <shell>
System.InvalidCastException: Creating an instance of the COM component with CLSID {D45FD2FC-5C6E-11D1-9EC1-00C04FD7081F}
from the IClassFactory failed due to the following error: 80004002.
这是由线程的问题引起的,解决的办法就是修改IronPythonConsole目录下PythonCommandLine.cs,在源代码的Main函数前增加[STAThread],
然后重新构建这个Solution。

MSDN上对80004002的定义是: Interface not supported error
见:Standard COM Errors
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/CS07Default/html/b88924d0-f9ca-41a5-af9e-66158ab795d2.asp

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2006/09/15/stathreadattribute/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham