Why does WPF require a STAThread attribute to be applied to the Main method?

后端 未结 2 905
自闭症患者
自闭症患者 2020-12-03 02:04

I am new to WPF, and in every tutorial I read, they either have a [System.STAThread] attribute applied to their Main method, or they tell the reade

2条回答
  •  生来不讨喜
    2020-12-03 02:38

    There's an excellent answer for this in this blog entry.

    Quoting from the blog:

    When the STAThreadAttribute is applied, it changes the apartment state of the current thread to be single threaded. Without getting into a huge discussion about COM and threading, this attribute ensures the communication mechanism between the current thread and other threads that may want to talk to it via COM. When you're using Windows Forms, depending on the feature you're using, it may be using COM interop in order to communicate with operating system components. Good examples of this are the Clipboard and the File Dialogs.

    Windows Forms is not supported within a MTA or free threaded apartment. Applications using Windows Forms should always declare the apartment style they're using, as some other component could initialize the apartment state of thread improperly.

提交回复
热议问题