gpt4 book ai didi

c# - SetApartmentState 和 [STAThread]

转载 作者:太空狗 更新时间:2023-10-29 18:25:18 24 4
gpt4 key购买 nike

在 Watin 的 source code ,有这段代码:

    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);
}

既然创建的线程设置了套间状态,为什么要在方法中添加[STAThread]属性呢?我对具体的代码片段不感兴趣,但我想知道是否需要 STAThread 属性。

注意事项:

  • GoToNoWaitInternal 方法未在别处使用。
  • 整个 watin 项目是关于操作 WebBrowser 对象(通常是 Internet Explorer 窗口)。因此,我们正在操纵 COM 对象。

最佳答案

只需阅读 STAThreadAttribute 的文档(强调我的):

Apply this attribute to the entry point method (the Main() method in C# and Visual Basic). 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.

因此,在这种情况下,该属性应该无效。

关于c# - SetApartmentState 和 [STAThread],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13603666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com