Andrey Bushman
Andrey Bushman

Reputation: 12516

Is STAThread attribute a requirement or recommendation?

I wrote managed extension for AutoCAD. When AutoCAD loads an extension it launch some IExtensionApplication.Initialize() method. I need this method would be launched in the main Thread of application. Is it enough to set the STAThread attribute for this method for this purpose? Is this attribute a requirement or recommendation?

Upvotes: 2

Views: 320

Answers (2)

Hans Passant
Hans Passant

Reputation: 942109

The [STAThread] attribute only works on the Main() entrypoint of a standalone executable program. It is a promise you make to the operating system, telling it that the main thread of your program is "well-behaved". It must pump a message loop and never block. Breaking the promise causes hard to diagnose misbehavior, deadlock is common.

None of this applies when you write an AutoCAD extension. You did not create the thread, AutoCAD did. You can't make any promises, it is AutoCAD that has to implement them. Nor is it a "main thread", that's a term that can only apply to a standalone program.

The thread that calls your extension is almost certainly already a single-threaded apartment, you can use Thread.GetApartmentState() in your code to double-check. STA is a requirement for a thread that displays UI, something that you very commonly do in an extension.

Upvotes: 4

Yochai Timmer
Yochai Timmer

Reputation: 49261

STA is a threading apartment policy for COM objects.
This threading policy is needed for many UI object that have an underlying implentation with COM objects.
That is why the main thread in a windows forms application is set to STA when you create a new project.

If you are not using any COM object that require the STA policy then you dont need that.

Upvotes: 2

Related Questions