STAThread 初学习集合

来源:互联网 发布:ubuntu 14.04 jdk1.8 编辑:程序博客网 时间:2024/05/16 03:52

http://blog.sina.com.cn/s/blog_4493d3b50100u6vi.html

[STAThread]--Single-Thread Apartment

 

在C#中用在Main()函数之前,指定当前线程的ApartmentState是STA,用在其他方法上没有作用。

有时根据设计需要,需要同COM进程进行交互,例如使用Windows clipboard。

以下引用另一同辈的发言:http://blog.csdn.net/qilang/archive/2006/06/06/775605.aspx


STA不是单线程的意思.英文为single threaded apartment.是一种套间(或译为公寓)线程模式.

sta thread并不表明应用程式的类型,和应用程序不搭界,恰相反,一个应用程序可以有多个线程.每个线程也可以有多个组件或对象.以前win16位系统的组件线程模式才真正是单线程.这是一种被淘汰了的模式.
线程模式用于处理组件在多线程的环境里并行与并互的方式.比如套间线程(STAThread)模式中接口跨线程传递必须被调度(Marshal),不调度直传肯定会失败!而MTA或FreeThread模式中的接口可以不经调度直接传递.
这种调度在特定的环境中非常影响性能(可有几百倍之差).如VB里只支持STAThread模式.FreeThread模式的组件会在里面表现成和跨进程一样慢!


线程模式是微软的COM基础中的极其重要的概念.一定要吃透!
我对.net真是一窍不通(没空去弄,对不起微软去年的奖赏).但我可以肯定,C#中的[STAThread]属性是应用程序的套间初始化代码.可以直接理解成SDK里的
CoInitialize(NULL);


初始一个STA套间实际上是相当于开了一个消息窗口,所有调用经此窗口过程调度到组件内.
同理[MTAThread](不知有没有这个属性,自已去查)
可以理解成
CoInitializeEx(NULL,COINIT_MULTITHREADED )
这经常是一个对初入com大门的人来说,有一定难度但必须过的一道关.
=====================================================================================

C#学习笔记(一)-- 入门的困惑
简单的我就不写了,主要写一下C#学习中的要点和难点。


1.由HelloWorld开始
先看一段基本上每本C#书里都会讲到的例子,很老土。

using System;namespace test{     class Class1     {         [STAThread]         static void Main(string[] args)         {              System.Console.WriteLine("Hello,World!");         }     }}


先引用一个命名空间System,再定义一个自己的命名空间test,里面有一个类Class1,属性[STAThread],一个入口的Main方法,注意:跟JAVA不一样,Main首名母是大写,Main必须是static的。不然怎么开始呢?难倒要实例化才行?哈哈,定义为static就是把它放在椎里。这里规举。
 
2.命名空间
再来看看System.Console.WriteLine("Hello,World!");输一名语名到控制台。调用System命名空间里的Console类的WriteLine方法。System命名空间是前面我们已经引用了的using System;
 
你也可以在引用的时候改个名字output,那么在调用的时候就是output.Console.WriteLine("Hello,World!");
试一试:
using output=System; namespace test{     class Class1     {         [STAThread]         static void Main(string[] args)         {              output.Console.WriteLine("Hello,World!");         }     }}

运行报错:F:\mydoc\Visual Studio Projects\test\Class1.cs(7): 找不到类型或命名空间名称“STAThread”(是否缺少 using 指令或程序集引用?)
嘿嘿,是[STAThread]惹的祸。干掉它。再试,搞定。
[STAThread]是Single  Thread  Apartment单线程套间的意思。是一种线程模型。其它的好像还是MTA(多线程套间)、Free  Thread(自由线程)。这个属性要加在主  Main  上。这个属性只在  Com  Interop 所用,如果全部是  managed  code  则无用。简单的说法:[STAThread]指示应用程序的默认线程模型是单线程单元 (STA)。启动线程模型可设置为单线程单元或多线程单元。如果未对其进行设置,则该线程不被初始化。
也就是说如果你用的.NET Framework,并且没有使用COM Interop,一般不需要这个Attribute。
 
明白了吧。
 
注意,using指令是用于命名空间的。变化着用一下,也可以为类创建别名:
using output=System.Console; namespace test{     class Class1     {         //[STAThread]         static void Main(string[] args)         {              output.WriteLine("Hello,World!");         }     }}

这样也行。。。
 
命令空间是可以嵌套的。如:
using System; namespace test{     namespace t1     {         class Class1         {              static void Main(string[] args)              {                   System.Console.WriteLine("t1.Class1");              }         }     }      namespace t2     {         class Class2         {              static void Main(string[] args)              {                   System.Console.WriteLine("t2.Class2");              }         }     }}

运行,报错。我是故意的(台下:大骗子)。J不要扔砖头啊。不要这么容易就放弃嘛,要执着。
看错误F:\mydoc\Visual Studio Projects\test\Class1.cs(9): 程序“F:\mydoc\Visual Studio Projects\test\obj\Debug\test.exe”定义了不止一个入口点:“test.t1.Class1.Main(string[])”
 
因为你的命名空间test里定义了二个Main方法,所以呢,不用我说了吧。
using System; namespace test{     namespace t1     {         class Class1         {              static void Main(string[] args)              {                   System.Console.WriteLine("t1.Class1");                   System.Console.WriteLine(t2.Class2.MyFunction());              }         }     }      namespace t2     {         class Class2         {              public static string MyFunction()              {                   return "t2.Class2";              }         }     }}

外部程序引用的时候就是这样:using test.t1;或using test.t2;
 
入门就这些问题。
打开Visual Studio .NET 2003 命令提示键入ILDASM,这个程序可以查看编译后的元数据。
 
网上查一下Reflector这个软件。干什么用的。反编译呀。。。。寒。
=========================================================================


单线程套间(STAThread) vs. 多线程套间(MTAThread )
[原文链接]:  STA Thread vs. MTAThread(WHost)

 

      最近我遇到一个有趣的线程问题,想跟大家分享一下,以免大家也遇到这种容易混淆的问题。

      打开一个其他人写的C#程序,为了下面的讲解,我把这个程序叫作”DeltaEngine”。DeltaEngine会调用一个本地的程序集,并处理其中某些事件。然后建一个工程,把DeltaEngine作为库项目引用,这个工程又被一个VB程序引用。我把这个VB程序叫做"VBApp"。所以,引用结构就像: 

      VBApp (VB) -> DeltaEngine (C#) -> NativeCode

      当我把VBApp作为启动程序运行时,它会一直等待NativeCode里面的事件在DeltaEngine中被处理。我注意到,如果我把DeltaEngine作为启动程序来运行的话,事件就会像预期那样得到处理。我花了很多时间想解决这个问题,但还是很困惑。

      最后有人指出,VB项目的默认线程模型是单线程套间(SingleThreaded  Apartment),而C#项目的默认线程模型是多线程套间 (Multithreaded Apartment)。因为DeltaEngine最初是作为C#工程开发的,被默认为使用MTA。当使用VBApp作为启动程序调用DeltaEngine时,DeltaEngine就会使用STA。因为这样,DeltaEngine就会开始等待其实它已经唤起的事件,所以DeltaEngine会一直等待下去。如果我把DeltaEngine作为启动程序运行,它就会使用MTA并且会像预期那样工作。

      解决的方法就是把MTAThreadAttribute加进VBApp的主函数里面。如下:

    <MTAThread> Sub Main()

      类似,如果你想把STAThread attribute加进C#的主方法里面,如下:

      [STAThread]

      static void Main()

      WindowsForms程序要求使用STA,所以创建C# Winapp后,你可以在Program.cs看见像这样的代码。

      我就不重复一些已经有的关于STATread 和MTAThread的文件,所以我给出下面的一些link可以学到更多关于STATread 和MTAThread的东西。

     STAThreadAttribute

      http://msdn2.microsoft.com/en-us/library/system.stathreadattribute(VS.71).aspx                           http://blogs.msdn.com/jfoscoding/archive/2005/04/07/406341.aspx

     MTAThreadAttribute

      http://msdn2.microsoft.com/en-us/library/system.mtathreadattribute(VS.71).aspx

======================================================================================
C# 中WindowsForm 的初始化信息 [STAThread]

    static class Program    {        /// <summary>        /// The main entry point for the application.        /// </summary>        [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.SetCompatibleTextRenderingDefault(false);            Application.Run(new Form1());        }    }

以上的代码是VS 2005中默认的初始化信息.

Application.EnableVisualStyles();

简单的说就是让你的控件显示出来.当然是在WindowsForm 中

此方法为应用程序启用可视样式。如果控件和操作系统支持视觉样式,则控件将以视觉样式进行绘制。若要使 EnableVisualStyles 生效,必须在应用程序中创建任何控件之前调用它;EnableVisualStyles 通常是 Main 函数的第一行.

 

下面的代码示例演示如何在 Main 函数中调用 EnableVisualStyles 来启用应用程序的视觉样式

对于支持FlatStyle属性的控件,请确保将FlatStyle属性设置为FlatStyle.System值。 

 

using System;using System.Drawing;using System.Windows.Forms; namespace VStyles{    public class Form1 : System.Windows.Forms.Form    {        private System.Windows.Forms.Button button1;         [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.Run(new Form1());        }         public Form1()        {            this.button1 = new System.Windows.Forms.Button();            this.button1.Location = new System.Drawing.Point(24, 16);            this.button1.Size = new System.Drawing.Size(120, 100);            this.button1.FlatStyle = FlatStyle.System;            this.button1.Text = "I am themed.";             // Sets up how the form should be displayed and adds the controls to the form.            this.ClientSize = new System.Drawing.Size(300, 286);            this.Controls.Add(this.button1);             this.Text = "Application.EnableVisualStyles Example";         }    }}



0 0
原创粉丝点击