简体   繁体   English

SetApartmentState和[STAThread]

[英]SetApartmentState and [STAThread]

In Watin's source code , there is this piece of code: 在Watin的源代码中 ,有这段代码:

    public void NavigateToNoWait(Uri url)
    {
        var thread = new Thread(GoToNoWaitInternal);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start(url);
        thread.Join(500);
    }

    [STAThread]
    private void GoToNoWaitInternal(object uriIn)
    {
        var uri = (Uri)uriIn;
        NavigateTo(uri);
    }

Since the thread created has its apartment state set, why is the [STAThread] attribute added to the method? 由于创建的线程设置了其单元状态,为什么[STAThread]属性被添加到方法中? I am not interested in the specific piece of code, but I am wondering if STAThread attribute is needed at all. 我对特定的代码段不感兴趣,但我想知道是否需要STAThread属性。

Notes: 笔记:

  • The method GoToNoWaitInternal isn't used elsewhere. 方法GoToNoWaitInternal不在别处使用。
  • The whole watin project is about manipulating WebBrowser objects (Internet explorer windows in general). 整个watin项目是关于操纵WebBrowser对象(一般的Internet Explorer窗口)。 Thus, we are manipulating a COM Object. 因此,我们正在操纵COM对象。

Just read the documentation for STAThreadAttribute (emphasis mine): 只需阅读STAThreadAttribute的文档(强调我的):

Apply this attribute to the entry point method (the Main() method in C# and Visual Basic). 将此属性应用于入口点方法(C#和Visual Basic中的Main()方法)。 It has no effect on other methods. 它对其他方法没有影响。 To set the apartment state of threads you start in your code, use the Thread.SetApartmentState method before starting the thread. 要设置从代码开始的线程的单元状态,请在启动线程之前使用Thread.SetApartmentState方法。

So, in this case, the attribute should have no effect. 因此,在这种情况下,该属性应该没有任何效果。

It should be noted that the STA (Single Threaded Apartment) is the threading model used by pre-.Net Visual Basic. 应该注意的是,STA(单线程单元)是pre-.Net Visual Basic使用的线程模型。 It should only be used on the Main method of components that will be exposed to COM. 它应仅用于将暴露给COM的组件的Main方法。 The author of the code that you are trying to understand, appearantly did not understand how it is supposed to be used. 您试图理解的代码的作者,显然不明白它应该如何使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM