Why are WinForms applications STAThread by default?

后端 未结 4 1624
醉话见心
醉话见心 2020-12-03 22:11

When you create an empty WinForms application with Visual Studio, the template has the STAThread attribute in the main application class.

4条回答
  •  盖世英雄少女心
    2020-12-03 22:41

    1. Why is this attribute added?

    Because it is required by the ActiveX object model. And you can drop ActiveX controls on a WinForm (so it is there for compatibility) OR some .NET classes use native controls which require that attribute.

    2. What does it mean?

    It means the thread runs in the single-threaded apartment model.

    3. What happens if you remove this attribute?

    If the attribute is removed, the behavior is undefined. The program may fail at random, with sometimes sensible error messages. For example, things may work now, then break with a service pack.

提交回复
热议问题